![](/img/trans.png)
[英]How do I get the properties from a subclass when I have the class but subclass name as a string
[英]How can I get the name of a class through a reference to an instance of a subclass?
如何通過引用子類的實例來獲取類的名稱?
例如,
public class BaseClass
{
public void ClassName()
{
// How can I get the name of the base class "BaseClass" here, without having to hardcode "BaseClass"?
Console.WriteLine(this.GetType().Name);
}
}
public class SubClass: BaseClass
{
public void ClassName()
{
base.ClassName();
Console.WriteLine(this.GetType().Name);
}
}
public static void Main(string[] args)
{
SubClass MyObject = new SubClass();
MyObject.ClassName();
}
輸出是
SubClass
SubClass
但我想要
BaseClass
SubClass
謝謝。
可能是最干凈的方法:
public static class TypeHelperExtensions
{
public static string GetTypeName<T>(this T Object)
{
return typeof(T).Name;
}
}
接着:
public class BaseClass
{
public virtual void ClassName()
{
// How can I get the name of the base class "BaseClass" here, without having to hardcode "BaseClass"?
Console.WriteLine(this.GetTypeName());
}
}
public class SubClass: BaseClass
{
public override void ClassName()
{
base.ClassName();
Console.WriteLine(this.GetTypeName());
}
}
public class BaseClass
{
public virtual void ClassName()
{
// How can I get the name of the base class "BaseClass" here, without having to hardcode "BaseClass"?
Console.WriteLine(nameof(BaseClass));
}
}
public class SubClass: BaseClass
{
public override void ClassName()
{
base.ClassName();
Console.WriteLine(nameof(SubClass));
}
}
public class BaseClass
{
public virtual void ClassName()
{
// If you know you will have only one parent
var b = type.BaseType.Name
}
}
如果您不知道其結構,則可能必須執行以下操作:
private bool _ignoreMe;
public void ClassName()
{
var b = this.GetType().GetField(nameof(_ignoreMe), BindingFlags.NonPublic | BindingFlags.Instance).DeclaringType;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.