【发布时间】:2013-03-07 20:08:57
【问题描述】:
我有一个基类 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();
返回“子模型”。这可能吗?
谢谢。
【问题讨论】:
-
你必须重写子类中的方法。
-
无需覆盖,使用 this.GetType().Name.... 但我担心您是否需要担心子类类型的名称。
-
在子类中调用GetType().Name即可;
-
安东尼拥有它。谢谢一堆。并且不要太担心我,只是用反射来解决问题,而不是在这里做任何严肃的工作。
标签: c# reflection