繁体   English   中英

如何从基类内部获取类的名称?

[英]How can I get the name of a class from inside the base class?

我有一个基类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();

返回“ SubModel”。 这可能吗?

谢谢。

您可以这样做:

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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM