通过在任何类之外声明的反射访问委托

本文关键字:反射 访问 声明 任何类 | 更新日期: 2023-09-27 18:09:18

我正在尝试一个反映的演示。我想在这门课上反映的程序集是这样的

namespace DelegatesSampleApplication
{
    delegate  bool IsPromotable (Employee employee); // Declaration Syntax is similar to that of a method's 
    class Program
    {
        public static void Main(string[] args)
        {
             //code goes here
        }
    }
    class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }
        public void PromoteEmployees(List<Employee> employeeList, IsPromotable isPromotableObj)
        {
            /*foreach (Employee employee in employeeList)
            {
                if (employee.Experience >= 5 && employee.Salary >= 10000) //That's a hard-coded logic that you have developed as a Framework Developer which makes the class itself not reusable
                {
                    Console.WriteLine(" {0} will be promoted in the next R.P. Cycle ", employee.EmployeeName);
                }
            }
            Console.ReadKey();*/
            foreach (Employee employee in employeeList)
            {
                if (isPromotableObj(employee)) 
                {
                    Console.WriteLine(" {0} will be promoted in the next R.P. Cycle ", employee.EmployeeName);
                }
            }
            Console.ReadKey();
        }
    }
}

现在我面临的问题是,我试图在我的程序中读取这个程序集,并试图调用在类实例中作为参数的委托。我要做的是在一个完全不同的类中执行类似的操作

  namespace ReflectionSample
{
    delegate bool empIsPromotable (Object obj);
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***************Loading External assembly*************");
            Assembly assembly = Assembly.LoadFrom(@"C:'Users'Chiranjib'Documents'visual studio 2012'Projects'DelegatesSampleApplication'DelegatesSampleApplication'bin'Debug'DelegatesSampleApplication.exe");
            Type employeeType = assembly.GetType("DelegatesSampleApplication.Employee"); //Gets the System.Type object for the Employee Class from the just loaded assembly with all it's dependencies
            Console.WriteLine("***************Loading External assembly properties*************");
           //Setting properties here
            Console.WriteLine("***************Creating an array list that will hold these employee instances***************");
            List<Object> employeeInstanceList = new List<object>();
            employeeInstanceList.Add(employeeInstance);
            employeeInstanceList.Add(employeeInstance2);
            Console.WriteLine("***************Invoking External assembly methods*************");
                        var args = new Object[] {
new List<employeeType>(),
(((employeeInstance) => { return true; }))

};

            Console.ReadKey();
        }
    }
}

这会抛出错误。说employeeType缺少程序集引用。另外,我不能将lambda表达式转换为对象。我不能直接类型转换为(IsPromotable)对吧?我在用反射。所以我应该没有直接访问权限。

我如何能够通过反射访问委托?请帮我渡过难关。

通过在任何类之外声明的反射访问委托

IsPromotable是不可调用的,它只是一个委托定义。把它想象成一个界面。它只是告诉你方法取什么和返回什么,但实际上并没有任何事情。

你可以这样调用PromoteEmployees:

PromoteEmployees(new List<Employee>, (employee) => { return employee.Name == "Rob"; });

任何与IsPromotable签名匹配的方法都是该方法的有效参数(即,任何接受Employee并返回bool的方法)。你能详细说明一下你到底想做什么吗?

如果你只想要一个委托列表,你可以这样做:

GetType().Assembly.GetTypes().Where(t => t.IsSubClassOf(typeof(BaseDelegate))); 

注意;这将只返回当前大会中的代表。您可以将其更改为:

typeof(Employee).GetTypes().Assembly.Where(t => t.IsSubClassOf(typeof(BaseDelegate))); 

要获取程序集中所有可浇注到IsPromotable的方法,可以这样做:

var delegateMethod = typeof(IsPromotable).GetMethod("Invoke");
var @params = delegateMethod.GetParameters();
var returnType = delegateMethod.ReturnType;
var matchingMethods = typeof(IsPromotable)
    .Assembly
    .GetTypes()
    .SelectMany(t => t.GetMethods())
    .Where(m => {
        if (m.ReturnType != returnType)
            return false;
        var currParams = m.GetParameters();
        if (currParams.Length != @params.Length)
            return false;
        for(var i = 0; i < currParams.Length;i++)
            if (currParams[i] != @params[i])
                return false;
        return true;
    });

要调用带有反射的方法,您可以这样做:

var args = new Object[] {
    new List<Employee>(),
    ((IsPromotable)((emp) => { return true; }))
};
var value = employeeType.InvokeMember("PromoteEmployees", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, employeeInstance, args);

或者,你可以给它传递一个常规方法:

var args = new Object[] {
    new List<Employee>(),
    ((IsPromotable)Test)
};
var value = employeeType.InvokeMember("PromoteEmployees", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, employeeInstance, args);

使用方法:

private bool Test(Employee emp)
{
    return false;
}