-4

首先,我不喜欢编程,但可以根据我的需要找出基本概念。

在下面的代码中,我想按名称“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);
4

3 回答 3

2

您正在尝试设置获取名为"ContractType"on的属性_cotreport并将其值设置为 on _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]);
于 2013-03-21T14:05:42.997 回答
1

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

像这样的东西:

System.Reflection.PropertyInfo PropertyInfo = _cotreport.GetType().GetProperty("Contract");
PropertyInfo.SetValue(_cotreport, COTReportHelper.ContractType.Gold, null);
于 2013-03-21T14:05:34.590 回答
0

此方法设置任何对象的属性值,如果分配成功则返回 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;
        }

    }
于 2013-03-21T14:16:01.843 回答