2012-08-26 50 views

回答

3

有很多的可能性...

基於實例:

private void SomeMethod(object list) // total generic 

成爲

private void SomeMethod(IEnumerable<object> list) // enumerable-generic 

private void SomeMethod(List<object> list) // explicit list 

或帶有通用功能:

private void SomeMethod<T>() where T : MyType // << contraints 
{ 
    var theType = typeof(T); 
} 

呼叫:

var xyz = SomeClass.SomeMethod<string>(); // for example 

有關約束的更多信息: http://msdn.microsoft.com/en-us/library/d5x73970(v=vs.80).aspx

+0

private void SomeMethod ()其中T:MyType 正是我所尋找的,我嘗試過類似的東西,但我對泛型很陌生,所以我沒有正確的語法。 – MichaelTaylor3D

7

嘗試使你的函數的通用,並傳遞類型參數通過泛型類型參數:

private void SomeMethod<T>() where T : U { 
    Type type = typeof(T); 
    // some stuff 
} 

您可以使用列出的任何類型約束here

如果它具有處理任意類型的對象(例如,當你沒有對誰調用功能控制),那麼你可能只需要使用運行時斷言:在

private void SomeMethod(System.Type type) 
{ 
    if(!typeof(U).IsAssignableFrom(type)) { 
     throw new ArgumentException("type must extend U!"); 
} 

又見這個問題Type Restriction