2015-11-20 119 views
1

在下面的代码,我想打电话,我在派生类中声明的方法:转换/投基类型派生泛型类型

class BaseClass 
{ 
    // ... 
} 
class A<T> : BaseClass 
{ 
    public void F(T args){ //... } 
} 
class B<T> : BaseClass 
{ 
    // B<T> doesn't have method F() 
} 
///.... 
class myApplication 
{ 
    // ... 
    public void DoSomething(BaseClass arg) 
    { 
     // Now I know that arg is of type A<T> for some type T 
     // but I don't know what T is. Also declaring DoSomething 
     // as DoSomething<T>() is not an option. 
     // 
     // I would like to call (arg as A<T>).F(...) but how can I 
     // deduce T? Can it be done in any other way? 
    } 
} 

请阅读代码中的注释。我该如何做这样的事情?

+0

你试过'class myApplication '? –

+1

假设你有你要传入F的对象,所以你不知道它的类型? –

回答

2

为了调用该方法,可以运行下面的代码:

class myApplication 
{ 
    // ... 
    public void DoSomething(BaseClass arg) 
    { 
     var type = arg.GetType(); 
     // Check whether a generic type was passed 
     if (type.IsGenericType) 
     { 
      var genType = type.GetGenericTypeDefinition(); 
      // Check whether it is of type A<> 
      if (genType == typeof(A<>)) 
      { 
       // Get generic argument type 
       var genArg = type.GenericTypeArguments[0]; 
       // Create a default instance; might not work under all circumstances 
       // Better to get the method parameter in another way 
       var mthArg = Activator.CreateInstance(genArg); 
       // Get method that is to be called 
       var mth = type.GetMethod("F"); 
       // Invoke method dynamically 
       mth.Invoke(arg, new object[] { mthArg }); 
      } 
     } 
    } 
} 

请注意,它T类型的参数传递给方法F是很重要的。你必须为此做好准备。在我的示例中,我添加了一个对Activator.CreateInstance的调用,它要求T有一个公共的默认构造函数(我用int进行测试)。

+0

不错!谢谢! – rashmatash