gpt4 book ai didi

c# - 在不使用静态类的情况下调用类的扩展方法,而是使用反射使用类 iteslf

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:27 25 4
gpt4 key购买 nike

我想调用 Method2,它是使用 MyClass 类型的 MyClass 的扩展方法。我想知道这是否可能。

using System;
using System.Linq;
using System.Reflection;

namespace ConsoleApplication9
{
public static class MyClassStatic
{
public static void Method2(this ConsoleApp2.MyClass obj)
{
Console.WriteLine("You have called ex Method 2");
}
}

public interface IClass
{
void Method1();
}

public class MyClass : ConsoleApp2.IClass
{
public void Method1()
{
Console.WriteLine("You have called Method 1");
}
}

class Program
{


public static void CallWhereMethod()
{


var whereMethods = typeof(MyClass)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(mi => mi.Name == "Method2");


Console.WriteLine(whereMethods.Count());
// returns zero

}

static void Main(string[] args)
{
CallWhereMethod();
Console.ReadKey();

}

}
}

最佳答案

这个其实是有办法的,就是有点难。如果您没有忘记将 this 关键字放置到您的扩展方法参数中,C#​​ 编译器将发出 ExtensionAttribute。到这个方法和这个类。知道了这一点,您就可以找到这个扩展方法并执行它:

var myClassType = typeof(MyClass);
var myClass = new MyClass();

var assemblyTypes = Assembly.GetExecutingAssembly().GetTypes();
foreach (var type in assemblyTypes.Where(t => t.GetCustomAttribute<ExtensionAttribute>() != null)
{
var typeMethods = type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (var method in typeMethods.Where(m => m.IsDefined(typeof(ExtensionAttribute), inherit: false))
{
if (method.GetParameters()[0].ParameterType == myClassType)
{
// here you go
method.Invoke(null, new object[]{ myClass });
}
}
}

如果您不确定在哪个程序集中搜索扩展方法,您可以尝试搜索所有:

var allLoadedTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes());

请注意反射。真的很慢。即使您使用 .Where(type => type.IsSealed) 或任何其他过滤器过滤所有类型,它仍然非常慢。如果您有任何其他方式来调用扩展方法中的代码,您可能应该使用这种方式。

关于c# - 在不使用静态类的情况下调用类的扩展方法,而是使用反射使用类 iteslf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53908839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com