是否有可能Class<T> Where T : IMySampleInterface
转换为Class<IMySampleInterface>
Convert类<T>其中T:IMySampleInterface到类<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始终是IC通信,那么为什么保持通用? - 达文特赖恩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实现协变接口01// IEnumerable。但类是不变的。 List list = new List(); //编译器错误此“ (http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx)
您需要在类级别而不是在方法级别定义''。 –
2013-03-08 14:58:23
在我的情况下,可以解决工作问题......如果'T'总是一个'ICommunication',我将很快解释 – frugi 2013-03-08 14:59:17
,那么为什么要保持通用? – 2013-03-08 15:00:44