簡體   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