是否有可能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