繁体   English   中英

将T投射为具有接口?

[英]Cast T as having an interface?

假设我有一个方法:

public void DoStuff<T>() where T : IMyInterface {
 ...
}

在其他地方,我想用其他方法调用

public void OtherMethod<T>() where T : class {
...
if (typeof(T) is IMyInterface) // have ascertained that T is IMyInterface
   DoStuff<T>();
}

有什么方法可以将T转换为具有我的界面?

DoStuff<(IMyInterface)T>和其他类似的变体对我不起作用。

编辑 :感谢您指出typeof(T) is IMyInterface是检查typeof(T) is IMyInterface的错误方法,而应在T的实际实例上调用。

Edit2 :我发现(IMyInterface).IsAssignableFrom(typeof(T))在检查接口时起作用。

我认为最简单的方法就是反思。 例如

public void OtherMethod<T>() where T : class {
    if (typeof(IMyInterface).IsAssignableFrom(typeof(T))) {
        MethodInfo method = this.GetType().GetMethod("DoStuff");
        MethodInfo generic = method.MakeGenericMethod(typeof(T));
        generic.Invoke(this, null);
    }
}

您可以使用相同的语法从多个接口继承:

public void OtherMethod<T>() where T : class, IMyInterface {
...
}

这行是错误的:

if (typeof(T) is IMyInterface) // have ascertained that T is IMyInterface
   DoStuff<T>();

typeof(T)返回一个Type ,它将永远不是IMyinterface 如果您有T的实例 ,则可以使用

if (instanceOfT is IMyInterface) // have ascertained that T is IMyInterface
   DoStuff<T>();

要么

if (instanceOfT is IMyInterface) // have ascertained that T is IMyInterface
   DoStuff<IMyInterface>();

否则,您可以按照Tim S的建议使用反射。

您的示例需要一些工作。 您在这里所做的工作很大程度上取决于您在DoStuff方法中如何使用IMyInterface。

您的DoStuff方法是否真的需要“ T”? 还是只需要“ IMyInterface”? 在我的示例中,我将一个对象传递给“ OtherMethod”,确定它是否实现IMyInterface”,调用DoStuff,并在该对象上调用接口方法。

您是否在传递物体? 在OtherMethod和DoStuff中如何使用类型“ T”和“ IMyInterface”?

如果您的DoStuff方法需要同时知道类型“ T”和接口“ IMyInterface”,则只需要通用的T:IMyInterface。

    public void DoStuff(IMyInterface myObject)
    {
        myObject.InterfaceMethod();
    }

    public void OtherMethod<T>(T myObject)
        where T : class
    {
        if (myObject is IMyInterface) // have ascertained that T is IMyInterface
        {
            DoStuff((IMyInterface)myObject);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM