Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 根据需要在运行时动态初始化对象_C# - Fatal编程技术网

C# 根据需要在运行时动态初始化对象

C# 根据需要在运行时动态初始化对象,c#,C#,鉴于我有一个结构如下的对象:- RootObject Personal Forename Surname Middlename Telephone LandLine Mobile 当我提供 <Ruleset> <Field>Personal.Forename</Field> <FieldValue>World</Field> </Ruleset&

鉴于我有一个结构如下的对象:-

RootObject
   Personal
      Forename
      Surname
      Middlename
   Telephone
      LandLine
      Mobile
当我提供

<Ruleset>
   <Field>Personal.Forename</Field>
   <FieldValue>World</Field>
</Ruleset>
<Ruleset>
   <Field>Personal.Surname</Field>
   <FieldValue>Hello</Field>
</Ruleset>

个人姓名
世界
个人姓
你好
当我设置供应商规则时

我希望根对象中的“Personal”对象在电话未初始化时根据需要进行初始化(反之亦然)


请告知我如何在不需要在整个RootObject子对象(和子对象的子对象)中编写初始化/构造函数代码的情况下实现这一点,因为我正在寻找一个动态解决方案,该解决方案无需对初始化代码段进行返工即可使用。谢谢

我不知道我是否理解正确,但是如果你想,你可以使用反射

如果
RuleSet
看起来像这样:

public class RulleSet
    {
         public string ObjectName { get; set; }
         public string PropertyName { get; set; }
         public object value { get; set; }
    }
您可以在类中创建方法:

public void Initialize(RulleSet initRule)
    {
        var initializableObject = this.GetType().GetProperty(initRule.ObjectName).GetValue(this,null);
        //If object not initialized, we need to create it
        if (initializableObject == null)
        {
            initializableObject =
                Activator.CreateInstance(this.GetType().GetProperty(initRule.ObjectName).PropertyType);
            PropertyInfo propertyInfo = this.GetType().GetProperty(initRule.ObjectName);
            propertyInfo.SetValue(this, Convert.ChangeType(initializableObject, propertyInfo.PropertyType), null);
        }
        //If we have object, we created it or it already axist doesn't matter we set property
        if (initializableObject != null)
        {
            var initializableProperty =
                initializableObject.GetType().GetProperty(initRule.PropertyName).GetValue(initializableObject, null);
            initializableProperty = Activator.CreateInstance(initializableObject.GetType().GetProperty(initRule.PropertyName).PropertyType);
            PropertyInfo propertyInfo = initializableObject.GetType().GetProperty(initRule.PropertyName);
            propertyInfo.SetValue(initializableObject, Convert.ChangeType(initializableProperty, propertyInfo.PropertyType), null);
        }
    }
未测试:),因此可能存在一些错误,如果您想使其成为静态的,只需在方法中添加表示您的初始化对象的附加参数,并用此参数替换

PS.ofc由于使用反射,可能会更慢,也不会进行编码初始化。

否决人请提供解释。这不是一个“家庭作业”,因为我已经尝试了几种方法,包括将其强制转换为object并执行.GetType(),然后初始化它。只要根对象中存在一个新类,我就必须更新整个GetType()开关。