我有一个A类方法
public IList<T> MyMethod<T>() where T:AObject
Run Code Online (Sandbox Code Playgroud)
我想在另一个泛型类B中调用此方法.此T没有任何约束.
public mehtodInClassB(){
if (typeof(AObject)==typeof(T))
{
//Compile error here, how can I cast the T to a AObject Type
//Get the MyMethod data
A a = new A();
a.MyMethod<T>();
}
}
Run Code Online (Sandbox Code Playgroud)
C类继承自AObject类.
B<C> b = new B<C>();
b.mehtodInClassB()
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
在提醒之后...更新:
是.我真正想做的是
typeof(AObject).IsAssignableFrom(typeof(T))
Run Code Online (Sandbox Code Playgroud)
不
typeof(AObject)==typeof(T))
Run Code Online (Sandbox Code Playgroud)
如果您知道这T是一个AObject,为什么不提供AObject类型参数MyMethod:
if (typeof(AObject).IsAssignableFrom(typeof(T)))
{
//Compile error here, how can I cast the T to a AObject Type
//Get the MyMethod data
d.MyMethod<AObject>();
}
Run Code Online (Sandbox Code Playgroud)
如果AObject作为类型参数提供不是一个选项,则必须T在调用方法中添加相同的约束:
void Caller<T>() where T: AObject
{
// ...
d.MyMethod<T>();
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1351 次 |
| 最近记录: |