0
我有一个基类BaseModel,和一个子类SubModel。我想在BaseModel中定义一个函数,它将返回类的字符串名称。我有这个工作的BaseClass的实例,但如果我做一个SubModel实例,该函数仍然返回“BaseModel”。这是代码?如何从基类中获取类的名称?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ClassLibrary1
{
public class BaseModel
{
public string GetModelName()
{
return MethodBase.GetCurrentMethod().ReflectedType.Name;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClassLibrary1;
namespace ConsoleApplication1
{
class SubModel : BaseModel
{
}
}
而且我想这个调用:
SubModel test = new SubModel();
string name = test.GetModelName();
要返回 “子模型”。这可能吗?
谢谢。
你不得不重写在子类中的方法。 – 2013-03-07 20:10:08
没有必要的重写,使用this.GetType()。名称....但我担心,如果你需要担心子类的名称类型。 – 2013-03-07 20:12:16
只需在子类中调用GetType()。 – 2013-03-07 20:13:03