通过反射同时设置多个属性

时间:2010-07-10 09:36:14

标签: c# reflection plinq

我正在尝试优化代码中的反射利用率,我很想知道 是否可以一次设置对象的多个属性:

样本用法:

private void SetProperties<T>(List<T> objects, List<Tuple<string, object>> propsAndValues) where T:Task
        {
            Type type = typeof(T);
            var propInfos = propsAndValues.ToDictionary(key => type.GetProperty(key.Item1, BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.SetProperty), elem => elem.Item2);

            objects.AsParallel().ForAll(obj =>
                {
                    obj.SetProps(propInfos);                                  
                });

        }

其中

public static void SetProps<T>(this T obj, Dictionary<PropertyInfo, object> propInfos) where T : Task
        {
            foreach (var propInfo in propInfos)
            {
                propInfo.Key.SetValue(obj, propInfo.Value, null);
            }            
        }

我希望SetProps扩展方法被更高效的东西取代,但还没有找到合适的东西。 在此先感谢;)

我已使用评论中提供的链接修改了代码。常规方式仍然快4倍。问题是这是限制还是有改进的余地?

class DelegateFactory
{
    public delegate void LateBoundPropertySet(object target, object value);

    public delegate void LateBoundPropertyListSet(object target, List<object> values);

    public static LateBoundPropertySet CreateSetIL(PropertyInfo property)
    {
        var method = new DynamicMethod("Set" + property.Name, null, new[] { typeof(object), typeof(object) }, true);
        var gen = method.GetILGenerator();

        var sourceType = property.DeclaringType;
        var setter = property.GetSetMethod(true);

        gen.Emit(OpCodes.Ldarg_0); // Load input to stack
        gen.Emit(OpCodes.Castclass, sourceType); // Cast to source type
        gen.Emit(OpCodes.Ldarg_1); // Load value to stack
        gen.Emit(OpCodes.Unbox_Any, property.PropertyType); // Unbox the value to its proper value type
        gen.Emit(OpCodes.Callvirt, setter); // Call the setter method
        gen.Emit(OpCodes.Ret);

        var result = (LateBoundPropertySet)method.CreateDelegate(typeof(LateBoundPropertySet));

        return result;
    }

    public static LateBoundPropertySet CreateSet(PropertyInfo property)
    {

        var setterType = typeof(Action<,>).MakeGenericType(property.DeclaringType, property.PropertyType);

        var propertyWriter = typeof(PropertyWriter<,>).MakeGenericType(property.DeclaringType, property.PropertyType);

        var setterDelegate = Delegate.CreateDelegate(setterType, property.GetSetMethod());

        var writer = (IPropertyWriter)Activator.CreateInstance(propertyWriter, setterDelegate);

        return writer.SetValue;

    }

    private interface IPropertyWriter
    {
        void SetValue(object instance, object value);
    }

    private interface IPropertyListWriter
    {

        void SetValues(object instance, List<object> values);

    }

    private class PropertyWriter<TInstance, TProperty> : IPropertyWriter
    {

        private readonly Action<TInstance, TProperty> _setValueDelegate;

        public PropertyWriter(Action<TInstance, TProperty> setValueDelegate)
        {

            _setValueDelegate = setValueDelegate;

        }

        public void SetValue(object instance, object value)
        {

            _setValueDelegate((TInstance)instance, (TProperty)value);
        }

    }

}

public static void SetProps2<T>(this T obj, Dictionary<DelegateFactory.LateBoundPropertySet, object> propSetters) where T : Task
    {                        
        foreach (var propSet in propSetters)
        {
            propSet.Key.Invoke(propSet, propSet.Value);
        }
    }

2 个答案:

答案 0 :(得分:4)

如果你正在做足够的反思,这是真正的瓶颈,那么动态代码可能值得研究。在此之前 - 也许HyperDescriptor会降低成本;非常相似的代码,但便宜得多。

在.NET 4.0及更高版本中,Expression API允许您设置多个属性,但这只有在缓存委托时才真正可行。另一个有趣的选项(具有相同的约束:您必须缓存并重新使用该委托)是DynamicMethod。但是,所有这些选项都是相当高级的主题。我很乐意提供建议,但你真的需要这个吗?

答案 1 :(得分:1)

正如Marc已经告诉过你的那样,最好使用动态代码来提高性能。

您可以使用GetSetMethod选择DynamicMethod方法或Delegate.CreateDelegate

对于DynamicMethod,您可以在此处查看示例:Late-Bound Invocations with DynamicMethod 至于CreateDelegate,请看一下这个问题:CreateDelegate with unknown types

相关问题