C# - 更快地获取设置公共静态字段而不是使用 Reflection.SetValue/GetValue [英] C# - Faster way to get set public static fields instead of using Reflection.SetValue / GetValue

查看:34
本文介绍了C# - 更快地获取设置公共静态字段而不是使用 Reflection.SetValue/GetValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个场景,我需要在运行时更改公共静态字段.我知道我可以通过如下反射来设置我想要的公共静态字段,但它真的很慢.

I have a scenario where I need to change public static fields during runtime. I understand that I can do it through reflection as below to get set the public static field I want, but it is really slow.

string typeName = "ABC";
string fieldName = "IsA";

Type.GetType(typeName ).GetField(fieldName ).SetValue(null, value);

var value = Type.GetType(typeName ).GetField(fieldName ).GetValue(null);

我想知道有没有更快的访问方式,例如使用 Reflection.Emit、Linq.Expression 或其他方法.据我所知,目前大多数只支持带有实例的字段.

I would like to know is there any faster way to access such as using Reflection.Emit, Linq.Expression or other methods. As what I know currently most of them only support fields with an instance.

推荐答案

您可以为此使用表达式.您基本上有三个选择:

You can use expressions for this. You basically have three options:

  1. 反思.慢.
  2. 动态编译表达式.快.
  3. 类型化的编译表达式.超快.

在您的情况下,使用类型表达式有点棘手.我想我们不能假设所有静态属性都是 string 类型?第二个选项允许您轻松地为任何字段类型创建快速设置器.

In your case it's a bit tricky to go for typed expressions. I guess we cannot assume that all static properties will be of type string? The second option allows you to easily create a fast setter for any field type.

请注意,在编译表达式时,您必须为已编译的委托维护一个缓存.编译步骤非常昂贵!

Note that when compiling expressions, you must maintain a cache for the compiled delegates. The compilation step is very expensive!

class Program
{
    public class Foo
    {
        public static string Name;
    }

    public static void Main()
    {
        var delegateCache = new Dictionary<(string, string), Delegate>();
        
        var typeName = typeof(Foo).FullName;
        var fieldName = "Name";

        var key = (typeName, fieldName);

        // Caching is crucial!
        if (!delegateCache.TryGetValue(key, out var d))
        {
            d = CreateStaticSetter(typeName, fieldName);
            delegateCache.Add(key, d);
        }

        // For a strongly typed delegate, we would use Invoke() instead.
        d.DynamicInvoke("new value");

        Console.WriteLine(Foo.Name);
    }

    private static Delegate CreateStaticSetter(string typeName, string fieldName)
    {
        var type = Type.GetType(typeName) ?? throw new ArgumentException();
        var field = type.GetField(fieldName) ?? throw new ArgumentException();
        
        var valueExp = Expression.Parameter(field.FieldType, "value");
        var fieldExp = Expression.Field(null, field);
        var assignExp = Expression.Assign(fieldExp, valueExp);

        // TODO: Can be further optimized with a strongly typed delegate.
        var expr = Expression.Lambda(assignExp, valueExp);
        return expr.Compile();
    }
}

这篇关于C# - 更快地获取设置公共静态字段而不是使用 Reflection.SetValue/GetValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆