【问题标题】:How can I get the name of a class from inside the base class?如何从基类中获取类的名称?
【发布时间】: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


【解决方案1】:

你可以这样做:

public class BaseModel
{
    public string GetModelName()
    {
        return this.GetType().Name;
    }
}

class SubModel : BaseModel
{

}

SubModel test = new SubModel();
string name = test.GetModelName();

这也是可能的:

string name = (test as BaseModel).GetModelName();
string name = ((BaseModel)test).GetModelName();

//both return "SubModel"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 2017-06-19
    • 2012-03-23
    • 2015-05-12
    • 2010-11-25
    相关资源
    最近更新 更多