简体   繁体   中英

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

I have a base class BaseModel, and and a subclass SubModel. I want to define a function inside BaseModel that will return the string name of the class. I have this working for instances of BaseClass, but if I make an SubModel instance, the function still returns "BaseModel". Here is the code?

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
    {

    }
}

And I would like this call:

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

To return "SubModel". Is this possible?

Thanks.

You can just do this:

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

class SubModel : BaseModel
{

}

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

This is also possible:

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

//both return "SubModel"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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