界面和委托投射

时间:2016-10-11 14:38:16

标签: c# .net interface delegates

代表:

    public delegate Result SalesforceAPIOnFailureEventHandler<T1, T2>(T1 sObject, T2 rawObject, string reason) where T1 : SalesforceApex.sObject;

接口:

    public interface iSalesforceAPIHelperConfiguration<T1, T2> where T1 : SalesforceApex.sObject
    {
        SalesforceAPIOnFailureEventHandler<T1, T2> OnFailure { get; set; }
    }

类别:

    public class SalesforceAPIHelperConfiguration<T1, T2> : iSalesforceAPIHelperConfiguration<T1, T2> where T1 : SalesforceApex.sObject
    {
       public SalesforceAPIOnFailureEventHandler<T1, T2> OnFailure { get; set; }
    }

功能:

    Type typeArg = typeof(SalesforceAPIHelperConfiguration<,>);
    Type[] typeArgs = { SalesforceApex.Account, typeof(object) };
    Type typeClass = typeArg.MakeGenericType(typeArgs);
    iSalesforceAPIHelperConfiguration<SalesforceApex.sObject, object> salesforceAPIHelperConfiguration = (iSalesforceAPIHelperConfiguration<SalesforceApex.sObject, object>)Activator.CreateInstance(typeClass);                    

基本上,我需要创建一个类型为SalesforceAPIHelperConfiguration的类,如上所示。我能够创建该类,但是我无法将其强制转换为我的界面。我怎么能做到这一点?

我的目的是创建SalesforceAPIHelperConfiguration类型的类并在运行时提供泛型参数。然后我需要初始化将通过接口公开的事件处理程序OnFailure。

1 个答案:

答案 0 :(得分:2)

关于T1T2,您的界面不变,因为它使用这些类型输出值,并使用这些类型接受值作为输入。由于它是不变的,因此您无法将iSalesforceAPIHelperConfiguration<someDerivedSFObject, someType>视为iSalesforceAPIHelperConfiguration<SalesforceApex.sObject, object>。如果运行时允许您这样做,那么您可以传入一个实际上与实际具体类型的实际泛型参数不匹配的对象(对于任一类型)。