草庐IT

c# - 在 C# 中动态创建用于 XmlSerializer 的属性

coder 2024-06-28 原文

我有一个接受 xml 消息的 API。假设我从这个 API 中获得了对象 Thing,如下所示:

<Thing shape="circle" color="red"/>

并映射到:

[XmlRoot("Thing")]
public class Thing {
    [XmlAttribute("shape")]
    public string Shape { get; set; }

    [XmlAttribute("color")]
    public string Color { get; set; }
}

现在我想更新这个对象,例如。颜色是绿色。 API 要求我以下列格式发送它:

<Thing color="green" o_color="red"/>

有没有办法即时生成 o_* 属性?因此,当它们在构造函数之外设置时,它们的旧值存储在 XmlSerializer 映射到 o_ 的某些生成的属性中?我知道我可以简单地手动创建这些属性,但对于更大的对象来说,这是一项乏味的工作。我已经尝试使用我已经在项目中使用的 CaSTLe 的动态代理来做到这一点,但它似乎无法添加这样的属性(或者我还没有找到如何做到这一点)

最佳答案

这里有几个问题需要解决。首先,您必须维护每个序列化对象的状态,这些状态会告诉您属性是否已更改,以及其原始值是多少。那么你的第二个问题是你需要根据这个维护的状态动态地构建一个新对象。使用我提供的实现,您将需要确定它是否满足您的性能需求,因为它进行了大量的反射。您还必须权衡其与其他解决方案的复杂性。我看到这个解决方案的优势是不必维护两个非常相似的对象。

<强>!!重要!! 此代码尚未准备好生产。我在代码中留下了一些需要清除的待办事项。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    public abstract class PropertyStateTracker
    {
        private class PropertyDetails
        {
            public object CurrentValue { get; set; }
            public bool HasChanged { get; set; }
            public object OriginalValue { get; set; }
        }

        private readonly Dictionary<string, PropertyDetails> propertyState =
            new Dictionary<string, PropertyDetails>();

        protected TProperty Get<TProperty>(Expression<Func<TProperty>> propertySelector)
        {
            string name = GetNameFromExpression(propertySelector);
            PropertyDetails data;
            if (!propertyState.TryGetValue(name, out data))
            {
                Set(propertySelector, default(TProperty));
                return default(TProperty);
            }
            return (TProperty)data.CurrentValue;
        }

        protected void Set<TProperty>(Expression<Func<TProperty>> propertySelector, TProperty value)
        {
            string name = GetNameFromExpression(propertySelector);
            PropertyDetails data;
            if (!propertyState.TryGetValue(name, out data))
            {
                data = new PropertyDetails() { OriginalValue = value, CurrentValue = value, HasChanged = false };
                propertyState[name] = data;
            }
            else
            {
                data.CurrentValue = value;
                data.HasChanged = true;
            }
        }

        [XmlIgnore]
        public IEnumerable<string> ChangedProperties
        {
            get
            {
                foreach (var property in propertyState)
                {
                    if (property.Value.HasChanged)
                    {
                        yield return property.Key;
                    }
                }
            }
        }

        public bool HasChanged<TProperty>(Expression<Func<TProperty>> propertySelector)
        {
            string name = GetNameFromExpression(propertySelector);
            return HasChanged(name);
        }

        public bool HasChanged(string propertyName)
        {
            EnsurePropertyExists(propertyName);
            PropertyDetails data;
            if (!propertyState.TryGetValue(propertyName, out data))
            {
                return false;
            }
            return data.HasChanged;
        }

        public TProperty GetOriginalValue<TProperty>(Expression<Func<TProperty>> propertySelector)
        {
            string name = GetNameFromExpression(propertySelector);
            return (TProperty)GetOriginalValue(name);
        }

        public object GetOriginalValue(string propertyName)
        {
            EnsurePropertyExists(propertyName);
            PropertyDetails data;
            if (!propertyState.TryGetValue(propertyName, out data))
            {
                return GetDefaultValue(GetPropertyInfo(propertyName).PropertyType);
            }
            return data.OriginalValue;
        }

        public TProperty GetCurrentValue<TProperty>(Expression<Func<TProperty>> propertySelector)
        {
            string name = GetNameFromExpression(propertySelector);
            return (TProperty)GetCurrentValue(name);
        }

        public object GetCurrentValue(string propertyName)
        {
            EnsurePropertyExists(propertyName);
            PropertyDetails data;
            if (!propertyState.TryGetValue(propertyName, out data))
            {
                return GetDefaultValue(GetPropertyInfo(propertyName).PropertyType);
            }
            return data.CurrentValue;
        }

        public void Reset()
        {
            foreach (var property in propertyState)
            {
                property.Value.OriginalValue = property.Value.CurrentValue;
                property.Value.HasChanged = false;
            }
        }

        private void EnsurePropertyExists(string propertyName)
        {
            PropertyInfo property = GetPropertyInfo(propertyName);
            if (property == null)
            {
                throw new ArgumentException(string.Format("A property named '{0}' was not found for type '{1}'",
                    propertyName, this.GetType().Name));
            }
        }

        private PropertyInfo GetPropertyInfo(string propertyName)
        {
            Type type = this.GetType();

            var property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            return property;
        }

        private static object GetDefaultValue(Type t)
        {
            if (t.IsValueType)
                return Activator.CreateInstance(t);

            return null;
        }

        private static string GetNameFromExpression<TMember>(Expression<Func<TMember>> lambda)
        {
            // check to make sure a non-null lambda was provided.
            if (lambda == null)
            {
                throw new ArgumentNullException("lambda");
            }

            Expression expression = lambda.Body;

            // is the expression's body a unary expression.
            var unaryExpression = expression as UnaryExpression;
            if (unaryExpression != null && unaryExpression.NodeType == ExpressionType.Convert)
            {
                expression = unaryExpression.Operand;
            }

            // is the expression's body a parameter expression.
            var parameterExpression = expression as ParameterExpression;
            if (parameterExpression != null)
            {
                return parameterExpression.Name;
            }

            // is the expression's body a member expression.
            var memberExpression = expression as MemberExpression;
            if (memberExpression != null)
            {
                return memberExpression.Member.Name;
            }

            // is the expression's body a method call expression.
            var methodCallExpression = expression as MethodCallExpression;
            if (methodCallExpression != null)
            {
                return methodCallExpression.Method.Name;
            }

            // unable to derive name. throw an exception.
            throw new Exception(
                string.Format("Failed to derive name from expression '{0}'",
                expression));
        }
    }



    [XmlRoot("Thing")]
    public class Thing : PropertyStateTracker
    {
        [XmlAttribute("shape")]
        public string Shape
        {
            get { return Get(() => Shape); }
            set { Set(() => Shape, value); }
        }

        [XmlAttribute("color")]
        public string Color
        {
            get { return Get(() => Color); }
            set { Set(() => Color, value); }
        }
    }


    class Program
    {

        private static long count = 0;

        static void Main(string[] args)
        {
            Thing thingInstance;
            System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(Thing));
            string rawData = "<Thing shape=\"circle\" color=\"red\"/>";
            using (System.IO.StringReader reader = new System.IO.StringReader(rawData))
            {
                thingInstance = (Thing)serializer.Deserialize(reader);
            }

            thingInstance.Color = "green";

            // these two variables should be reused every time a new proxy is created. you dont want too many dynamic assemblies.
            var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("DynamicThingAssembly"), AssemblyBuilderAccess.Run);
            var moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicThingModule");

            // TODO: need to figure out a way to reuse the proxyTypes being generated or you will have a 
            // memory leak. the type is unique based on the properties that have been modified, so you should be able to use 
            // the state stored inside of thingInstance to figure this out. I leave this up to you to implement.
            Type proxyType = CreateProxy(moduleBuilder, thingInstance);
            var proxy = Activator.CreateInstance(proxyType);

            foreach (var propertyName in thingInstance.ChangedProperties)
            {

                proxyType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)
                    .SetValue(proxy, thingInstance.GetCurrentValue(propertyName));
                proxyType.GetProperty("O_" + propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)
                    .SetValue(proxy, thingInstance.GetOriginalValue(propertyName));
            }

            // Important this XmlSerializer should be cached, otherwise you will have a memory leak in your program.
            System.Xml.Serialization.XmlSerializer serializer2 = new XmlSerializer(proxyType, new XmlRootAttribute("Thing"));

            StringBuilder sb = new StringBuilder();
            using (System.IO.StringWriter writer = new System.IO.StringWriter(sb))
            {
                serializer2.Serialize(writer, proxy);
            }

            Console.Write(sb.ToString());
        }

        private static Type CreateProxy(ModuleBuilder moduleBuilder, Thing thing)
        {
            var typeName = "DynamicType" + System.Threading.Interlocked.Increment(ref count).ToString("X5");
            TypeBuilder typeBuilder = moduleBuilder.DefineType(typeName, TypeAttributes.Public);

            Type t = typeof(Thing);
            foreach (var propertyName in thing.ChangedProperties)
            {
                var propertyInfo = t.GetProperty(propertyName,
                    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);

                CreateProperty(typeBuilder, propertyInfo.Name, propertyInfo.PropertyType);
                CreateProperty(typeBuilder, "O_" + propertyInfo.Name, propertyInfo.PropertyType);
            }

            return typeBuilder.CreateType();
        }

        private static void CreateProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType)
        {
            var fieldBuilder = typeBuilder.DefineField("_" + propertyName, propertyType, FieldAttributes.Private);

            // The last argument of DefineProperty is null, because the
            // property has no parameters. (If you don't specify null, you must
            // specify an array of Type objects. For a parameterless property,
            // use an array with no elements: new Type[] {})
            var propertyBuilder = typeBuilder.DefineProperty(
                propertyName, PropertyAttributes.HasDefault, propertyType, null);


            var attributeConstructor = typeof(XmlAttributeAttribute).GetConstructor(new Type[] { typeof(string) });
            propertyBuilder.SetCustomAttribute(
                new CustomAttributeBuilder(
                    attributeConstructor,
                    new object[] { propertyName.ToLower() }));


            // The property set and property get methods require a special
            // set of attributes.
            MethodAttributes getSetAttr =
                MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig;


            MethodBuilder getPropertyMethodBuilder =
                typeBuilder.DefineMethod("get_" + propertyName,
                                  getSetAttr,
                                  propertyType,
                                  Type.EmptyTypes);

            // Create the get methods body.
            ILGenerator getPropertyMethodILGenerator = getPropertyMethodBuilder.GetILGenerator();
            getPropertyMethodILGenerator.Emit(OpCodes.Ldarg_0);
            getPropertyMethodILGenerator.Emit(OpCodes.Ldfld, fieldBuilder);
            getPropertyMethodILGenerator.Emit(OpCodes.Ret);


            // Define the "set" accessor method for CustomerName.
            MethodBuilder setPropertyMethodBuilder =
                typeBuilder.DefineMethod("set_" + propertyName,
                                           getSetAttr,
                                           null,
                                           new Type[] { propertyType });

            // Create the set methods body.
            ILGenerator setPropertyMethodILGenerator = setPropertyMethodBuilder.GetILGenerator();
            setPropertyMethodILGenerator.Emit(OpCodes.Ldarg_0);
            setPropertyMethodILGenerator.Emit(OpCodes.Ldarg_1);
            setPropertyMethodILGenerator.Emit(OpCodes.Stfld, fieldBuilder);
            setPropertyMethodILGenerator.Emit(OpCodes.Ret);

            // Last, we must map the two methods created above to our PropertyBuilder to 
            // their corresponding behaviors, "get" and "set" respectively. 
            propertyBuilder.SetGetMethod(getPropertyMethodBuilder);
            propertyBuilder.SetSetMethod(setPropertyMethodBuilder);



        }
    }
}

关于c# - 在 C# 中动态创建用于 XmlSerializer 的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946286/

有关c# - 在 C# 中动态创建用于 XmlSerializer 的属性的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  3. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  4. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  5. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  6. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  7. ruby-on-rails - 在混合/模块中覆盖模型的属性访问器 - 2

    我有一个包含模块的模型。我想在模块中覆盖模型的访问器方法。例如:classBlah这显然行不通。有什么想法可以实现吗? 最佳答案 您的代码看起来是正确的。我们正在毫无困难地使用这个确切的模式。如果我没记错的话,Rails使用#method_missing作为属性setter,因此您的模块将优先,阻止ActiveRecord的setter。如果您正在使用ActiveSupport::Concern(参见thisblogpost),那么您的实例方法需要进入一个特殊的模块:classBlah

  8. ruby - 如何使用 RSpec::Core::RakeTask 创建 RSpec Rake 任务? - 2

    如何使用RSpec::Core::RakeTask初始化RSpecRake任务?require'rspec/core/rake_task'RSpec::Core::RakeTask.newdo|t|#whatdoIputinhere?endInitialize函数记录在http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method没有很好的记录;它只是说:-(RakeTask)initialize(*args,&task_block)AnewinstanceofRake

  9. ruby - 多个属性的 update_column 方法 - 2

    我有一个具有一些属性的模型:attr1、attr2和attr3。我需要在不执行回调和验证的情况下更新此属性。我找到了update_column方法,但我想同时更新三个属性。我需要这样的东西:update_columns({attr1:val1,attr2:val2,attr3:val3})代替update_column(attr1,val1)update_column(attr2,val2)update_column(attr3,val3) 最佳答案 您可以使用update_columns(attr1:val1,attr2:val2

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐