无法将匿名委托分配给已签名的委托

时间:2018-11-11 12:17:05

标签: c# delegates anonymous-delegates

我正在寻找一种将列表中的不同委托分配给MethodInfo的方法,而无需事先获得有关返回类型的信息。以下是我正在使用的代码。这些评论提供了有关正在发生的事情的其他信息。这是一长段代码,但我已尽力减少了。

主要代码段

private const string methodName = "Execute";

    public static void Main()
    {
        ExampleClass1 e1 = new ExampleClass1();
        ExampleClass2 e2 = new ExampleClass2();
        ExampleClass3 e3 = new ExampleClass3();

        /* Code below Simulates:  "e3.GetString = e2.Execute;" */
        var method = e2.GetType().GetMethod(methodName);

        for (int i = 0; i < e3.DelegateList.Count; i++)
        {
            // First check the type of e2 return
            Type methodType = method.ReturnType;

            // Check that its the same return type as delegate
            if (methodType != e3.DelegateList[i].ReturnType)
                continue;

            // Assign delegate to method
            var returnType = e3.DelegateList[i].DelegateType;
            e3.DelegateList[i].Delegate = Delegate.CreateDelegate(returnType, e2, method);

            /* Code below only for debugging */
            Console.WriteLine("The delegate in the list: " + e3.DelegateList[i].Delegate);// Returns Type of StringHandler
            Console.WriteLine("The delegate in the object: " + e3.GetString);// Returns null
            e3.GetString = e3.DelegateList[i].Delegate;// This throws Error Cannot convert Delegate to StringHandler
        }

        /* Code above Simulates:  "e3.GetString = e2.Execute;" */

        e2.GetNumber = e1.Execute;

        e3.Execute();// Throws Null References Exception on

        // Read the key
        Console.ReadKey();
    }

支持的课程/代码

如果您需要有关支持课程的更多信息,请参见下面的代码。此外,这是一个自包含的程序,应按原样运行。

 public class ExampleClass3
{
    public delegate string StringHandler();

    public delegate int IntHandler();

    public StringHandler GetString { get; set; }
    public IntHandler GetInt { get; set; }

    public List<DelegateInfo<Type, Type, Delegate>> DelegateList { get; set; }

    public ExampleClass3()
    {
        DelegateList = new List<DelegateInfo<Type, Type, Delegate>>();
        DelegateList.Add(new DelegateInfo<Type, Type, Delegate>(typeof(StringHandler), typeof(string), GetString));
        DelegateList.Add(new DelegateInfo<Type, Type, Delegate>(typeof(IntHandler), typeof(int), GetInt));
    }

    public object Execute()
    {
        Console.WriteLine(GetString());

        return null;
    }
}

public class ExampleClass2
{
    public delegate int NumberHandler();

    public NumberHandler GetNumber { get; set; }

    public string Execute() => $"Your Number Is {GetNumber()}";
}

public class ExampleClass1
{
    public int number = 5;

    public int Execute() => number;
}

public class DelegateInfo<T1, T2, T3>
{
    public DelegateInfo(T1 delegateType, T2 returnType, T3 @delegate)
    {
        DelegateType = delegateType;
        ReturnType = returnType;
        Delegate = @delegate;
    }

    public T1 DelegateType { get; set; }
    public T2 ReturnType { get; set; }
    public T3 Delegate { get; set; }
}

2 个答案:

答案 0 :(得分:1)

我稍微简化了您的代码,以演示如何实现此目的。首先,不要创建特殊的DelegateInfo类-尽量使用标准的.NET反射库。他们在这方面做得非常好-但是学习起来确实需要一段时间。

代码如下:

this.execute

首先,请注意我如何摆脱了对Func的自定义委托定义。这将证明以通用方式更容易使用。请注意,现在如何定义ExampleClass3:

couchbase.BucketImpl.LookupInBuilder.prototype.execute

我可以使用所有这些函数都是Func类型的事实来开发通用解决方案,为它们分配一个值。根据目标方法的返回类型,我可以构造适当类型的Func委托(并将其链接到所讨论的特定e2实例):

data a;
input name$ id age;
cards;
Ruth 39 11
Jose 32 22
Sue 30 33
John 40 44
;
run;

data _null_;
set a;
file 'C:\Users\stardust\Desktop\employee';
If _N_ = 1 then do;
Put "----|---10----|---20---";
end;
put name 1-4 id 6-7 age 9-10;
run;

现在,我可以直接将该委托分配为具有匹配委托类型的任何属性的值:

    private const string methodName = "Execute";

    public static void Main()
    {
        ExampleClass1 e1 = new ExampleClass1();
        ExampleClass2 e2 = new ExampleClass2();
        ExampleClass3 e3 = new ExampleClass3();

        /* Code below Simulates:  "e3.GetString = e2.Execute;" */
        var method = e2.GetType().GetMethod(methodName);            
        Type methodType = method.ReturnType;

        // Create a Func<T> that will invoke the target method            
        var funcType = typeof(Func<>).MakeGenericType(methodType);
        var del = Delegate.CreateDelegate(funcType, e2, method);

        var properties = e3.GetType().GetProperties();
        for (int i = 0; i < properties.Length; i++)
        {              
            if (properties[i].PropertyType.IsAssignableFrom(funcType)) {
                properties[i].SetValue(e3, del );
            }
        }

        /* Code above Simulates:  "e3.GetString = e2.Execute;" */

        e2.GetNumber = e1.Execute;

        e3.Execute();

        // Read the key
        Console.ReadKey();
    }
    public class ExampleClass3
    {         
        public Func<String> GetString { get; set; }
        public Func<int> GetInt { get; set; }

        public ExampleClass3()
        { }

        public object Execute()
        {
            Console.WriteLine(GetString());
            return null;
        }
    }

    public class ExampleClass2
    {
        public Func<int> GetNumber { get; set; }

        public string Execute() => $"Your Number Is {GetNumber()}";
    }

    public class ExampleClass1
    {
        public int number = 5;

        public int Execute() => number;
    }

希望有帮助:)

答案 1 :(得分:0)

他们是演员失踪了:

e3.GetString = (ExampleClass3.StringHandler)e3.DelegateList[i].Delegate;