【发布时间】:2013-03-08 14:53:51
【问题描述】:
是否可以将Class<T> Where T : IMySampleInterface 转换为Class<IMySampleInterface>
例子:
public abstract class AbstractCommunication: ICommunication
{
private ICommunicationCallback<ICommunication> callback = null;
public void registerCommunicationCallback<T>(ICommunicationCallback<T> callback) where T : ICommunication
{
this.callback = (ICommunicationCallback<ICommunication>)callback; //<--DOESNT WORK
}
}
在我的示例中出现以下异常:System.InvalidCastException
编辑:
public interface ICommunicationCallback<T> where T : ICommunication
{
void onCommunicationCallback(T sender, String data);
}
我为什么要使用这种方式:如果我有一个基类应该实现例如两个回调,那么我可以简单地使用以下内容:
public class TestClass : ICommunicationCallback<TestClass1>, ICommunicationCallback<TestClass2>
TestClass1:
public class TestClass1: AbstractCommunication
{
}
TestClass2:
public class TestClass2: AbstractCommunication
{
}
编辑: “如果 T 始终是一个 ICommunication,那么为什么要保持其通用性?—— Davin Tryon 20 分钟前”我锁定在这一点上
好的,如果没有泛型,我得到了相同的错误,但不同 System.InvalidCastException:
(这就是我一开始使用泛型的原因——我现在记得了)
public class DocumentTest : ICommunicationCallback<GetDocumentData>
{
public void callAsync()
{
CommunicationFactory comFactory = new CommunicationFactory(communicationServiceClient);
GetDocumentData getDocumentData = (GetDocumentData)comFactory.createCommunicationObject(CommunicationFactory.ENTITY_TYPE.GET_DOCUMENT_DATA,(ICommunicationCallback<ICommunication> ) this);
}
}
public interface ICommunicationCallback<ICommunication>
{
void onCommunicationCallback(ICommunication sender, String data);
}
我认为使用泛型是我的唯一解决方案 - 请参阅: “此功能仅适用于泛型接口和委托。如果您实现变体泛型接口,则实现类仍然是不变的。类和结构不支持 C# 4.0 中的变体。 因此以下内容无法编译: // List 实现协变接口 // IEnumerable。但是类是不变的。 列表列表 = 新列表(); // 这里的编译器错误。” (http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx)
【问题讨论】:
-
你需要在类级别定义
<T>,而不是在方法级别。 -
在我的情况下,它确实有效......我会尽快解释
-
如果
T始终是ICommunication,那么为什么要保持其通用性?
标签: c#