2010-10-01 81 views
3

我想確定是否將MyBindingSource.DataSource分配給設計器集合Type,或者是否已分配了對象實例。這是我目前(相當醜陋的)解決方案:C# - 在運行時確定屬性是Type還是Object實例?

Type sourceT = MyBindingSource.DataSource.GetType(); 
if(sourceT == null || sourceT.ToString().Equals("System.RuntimeType")) { 
    return null; 
} 
return (ExpectedObjType) result; 

System.RuntimeType是私有的,不可接近的,所以我不能做到這一點:

Type sourceT = MyBindingSource.DataSource.GetType(); 
if (object.ReferenceEquals(sourceT, typeof(System.RuntimeType))) { 
    return null; 
} 
return (ExpectedObjType) result; 

我只是想知道,如果一個更好的解決方案存在?特別是不依賴於Type名稱的一個。

回答

1

由於System.RuntimeTypeSystem.Type衍生,你應該能夠做到以下幾點:

object result = MyBindingSource.DataSource; 
if (typeof(Type).IsAssignableFrom(result.GetType())) 
{ 
    return null; 
} 
return (ExpectedObjType)result; 

或更簡潔:

object result = MyBindingSource.DataSource; 
if (result is Type) 
{ 
    return null; 
} 
return (ExpectedObjType)result; 

巧合的是,這是所採取的方法here

+0

正是我在找的,謝謝! – Rob 2010-10-01 17:29:46

1

你不必ToString()它;你應該可以通過GetType()來訪問它的名字(這幾乎是一回事)。無論哪種方式,因爲它是一個私有類,並且不能從開發者代碼訪問,所以如果你需要驗證它是否是一個RuntimeType,我認爲你被困在一個「魔術字符串」中。並非所有「最佳解決方案」都儘可能優雅。

如果您將獲得的所有類型參數實際上都是RuntimeType對象,那麼您可以按照其他答案中的建議查找基類。但是,如果您可以收到一個不是RuntimeType的類型,則會出現一些「誤報」。

相關問題