![](/img/trans.png)
[英]How to retrieve the name of type T? I'm always getting “RuntimeType”
[英]How to determine if a Type is of RunTimeType?
如何確定 Type 是否屬於 RunTimeType 類型? 我有這個工作,但它有點笨拙:
private bool IsTypeOfType(Type type)
{
return type.FullName == "System.RuntimeType";
}
我猜您實際上想知道Type
對象是否描述了Type
類,但是Type
對象是typeof(RuntimeType)
而不是typeof(Type)
,因此將其與typeof(Type)
進行比較失敗。
您可以做的是檢查是否可以將Type
對象描述的Type
的實例分配給Type
的變量。 這給出了所需的結果,因為RuntimeType
派生自Type
:
private bool IsTypeOfType(Type type)
{
return typeof(Type).IsAssignableFrom(type);
}
如果你真的需要知道描述Type
類的Type
對象,可以使用GetType方法:
private bool IsRuntimeType(Type type)
{
return type == typeof(Type).GetType();
}
但是,因為typeof(Type) != typeof(Type).GetType()
,您應該避免這種情況。
例子:
IsTypeOfType(typeof(Type)) // true
IsTypeOfType(typeof(Type).GetType()) // true
IsTypeOfType(typeof(string)) // false
IsTypeOfType(typeof(int)) // false
IsRuntimeType(typeof(Type)) // false
IsRuntimeType(typeof(Type).GetType()) // true
IsRuntimeType(typeof(string)) // false
IsRuntimeType(typeof(int)) // false
真的,唯一的麻煩是System.RuntimeType
是internal
,所以做一些簡單的事情:
if (obj is System.RuntimeType)
不編譯:
CS0122 'RuntimeType' 由於其保護級別而無法訪問。
所以上面@dtb 的解決方案是正確的。 擴展他們的答案:
void Main()
{
object obj = "";
// obj = new {}; // also works
// This works
IsRuntimeType(obj.GetType()); // Rightly prints "it's a System.Type"
IsRuntimeType(obj.GetType().GetType()); // Rightly prints "it's a System.RuntimeType"
// This proves that @Hopeless' comment to the accepted answer from @dtb does not work
IsWhatSystemType(obj.GetType()); // Should return "is a Type", but doesn't
IsWhatSystemType(obj.GetType().GetType());
}
// This works
void IsRuntimeType(object obj)
{
if (obj == typeof(Type).GetType())
// Can't do `obj is System.RuntimeType` -- inaccessible due to its protection level
Console.WriteLine("object is a System.RuntimeType");
else if (obj is Type)
Console.WriteLine("object is a System.Type");
}
// This proves that @Hopeless' comment to the accepted answer from @dtb does not work
void IsWhatSystemType(object obj)
{
if (obj is TypeInfo)
Console.WriteLine("object is a System.RuntimeType");
else
Console.WriteLine("object is a Type");
}
在這里工作 .NET 小提琴。
return type == typeof(MyObjectType) || isoftype(type.BaseType) ;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.