Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/275.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从基类内部获取类的名称?_C#_Reflection - Fatal编程技术网

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

C# 如何从基类内部获取类的名称?,c#,reflection,C#,Reflection,我有一个基类BaseModel和一个子类SubModel。我想在BaseModel中定义一个函数,该函数将返回类的字符串名称。对于基类的实例,我可以这样做,但是如果我创建了一个子模型实例,该函数仍然返回“BaseModel”。这是密码 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ClassLibra

我有一个基类BaseModel和一个子类SubModel。我想在BaseModel中定义一个函数,该函数将返回类的字符串名称。对于基类的实例,我可以这样做,但是如果我创建了一个子模型实例,该函数仍然返回“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();
返回“子模型”。这可能吗

谢谢

您可以这样做:

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"

您必须重写子类中的方法。无需重写,请使用此.GetType().Name。。。。但是如果您需要担心子类类型的名称,我会担心;安东尼有。非常感谢。别为我担心太多,只是思考,不做任何严肃的工作。