【问题标题】:C# how Set property dynamically by string?C#如何通过字符串动态设置属性?
【发布时间】:2013-03-11 02:12:39
【问题描述】:

首先,我不喜欢编程,但可以弄清楚基本概念 满足我的需要。

在下面的代码中,我想按名称“Gold”设置属性,如下所示:

_cotreport.Contract = COTReportHelper.ContractType."Blabalbal"


 protected override void OnBarUpdate()
            {

                COTReport _cotreport = COTReport(Input);
                _cotreport.Contract=COTReportHelper.ContractType.Gold;
                _cotreport.OpenInterestDisplay=COTReportHelper.OpenInterestDisplayType.NetPosition;
                double index = _cotreport.Commercial[0];
                OwnSMA.Set(index);

            } 

我尝试了下面的代码,但系统说:“

对象引用未设置为对象的实例”

请帮忙!

            System.Reflection.PropertyInfo PropertyInfo = _cotreport.GetType().GetProperty("ContractType");
            PropertyInfo.SetValue(_cotreport.Contract,"Gold",null);
            PropertyInfo.SetValue(_cotreport.Contract,Convert.ChangeType("Gold",PropertyInfo.PropertyType),null);

【问题讨论】:

  • 提问前先打谷歌
  • “打码”?不错...

标签: c# dynamic reflection properties set


【解决方案1】:

您正在尝试在_cotreport 上设置一个名为"ContractType" 的属性,并在_cotreport.Contract 上设置它的值。这行不通有两个原因。

  1. 属性名称(从我在您的代码中可以看出)是 Contract 而不是 ContractType
  2. 您需要在_cotreport 上设置值。

试试这个

System.Reflection.PropertyInfo property = _cotreport.GetType().GetProperty("Contract");
property.SetValue(_cotreport, COTReportHelper.ContractType.Gold, new object[0]);

如果您想按名称设置枚举值,这是一个单独的问题。试试这个

var enumValue = Enum.Parse(typeof(COTReportHelper.ContractType), "Gold");
property.SetValue(_cotreport, enumValue, new object[0]);

【讨论】:

  • var enumValue = Enum.Parse(typeof(COTReportHelper.ContractType), "Gold"); property.SetValue(_cotreport, enumValue, new object[0]);是解决方案,非常感谢!!!!!!
  • @user2195345 很高兴我能帮上忙
【解决方案2】:

此方法设置任何对象的属性值,如果分配成功则返回true:

public static Boolean TrySettingPropertyValue(Object target, String property, String value)
{
        if (target == null)
            return false;
        try
        {
            var prop = target.GetType().GetProperty(property, DefaultBindingFlags);
            if (prop == null)
                return false;
            if (value == null)
                prop.SetValue(target,null,null);
            var convertedValue = Convert.ChangeType(value, prop.PropertyType);
            prop.SetValue(target,convertedValue,null);
            return true;
        }
        catch
        {
            return false;
        }

    }

【讨论】:

  • 谢谢,错误:当前上下文中不存在名称“DefaultBindingFlags”。
【解决方案3】:

PropertyInfo可能是null,如果您使用属性名称可能不是:Contract。您应该能够直接指定COTReportHelper.ContractType.Gold 作为值。并且您将 property 指定为要修改的实例,但 PropertyInfo 表示,您应该指定应在其上设置属性值的拥有实例。

类似这样的:

System.Reflection.PropertyInfo PropertyInfo = _cotreport.GetType().GetProperty("Contract");
PropertyInfo.SetValue(_cotreport, COTReportHelper.ContractType.Gold, null);

【讨论】:

    猜你喜欢
    • 2012-03-21
    • 1970-01-01
    • 2023-03-30
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-11
    • 2010-11-08
    • 2019-03-12
    相关资源
    最近更新 更多