-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

on という名前のプロパティを取得し、その値を on で"ContractType"設定しようとしています。それは 2 つの理由で機能しません。_cotreport_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、プロパティ名を使用した場合はそうではない可能性があります: ContractCOTReportHelper.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 に答える