【问题标题】:How to find generic property name of class instance and how to assign value to the property run time如何查找类实例的通用属性名称以及如何为属性运行时赋值
【发布时间】:2011-11-17 16:53:52
【问题描述】:

我有以下课程。在 BE(比如说 objBE)的实例中,我想在运行时选择属性名称并为其赋值。例如我们有一个包含所有属性的组合,并且在窗口窗体上有文本框和命令按钮。我想从组合中选择属性名称并在文本框中键入一些值,然后单击按钮我想从 objBE 中查找属性名称并将文本框值分配给选定的属性。无法解决如何完成它。可以帮忙。 提前致谢。 H N

public class MyPropertyBase
{
    public int StartOffset { get; set; }
    public int EndOffset { get; set; }
}

public class MyProperty<T> : MyPropertyBase
{
    public MyProperty(T propertyValue)
    {
        PropertyValue = propertyValue;
    }

    public T PropertyValue { get; set; }

    public static implicit operator MyProperty<T>(T t)
    {
        return new MyProperty<T>(t);
    }
}

public class BE
{
    private List<Admin_Fee> _Admin_Fee = new List<Admin_Fee>();

    public MyProperty<int> RFID
    {get;set;}
    public MyProperty<string> CUSIP
    {get;set;}
    public MyProperty<string> FUND_CITY 
    {get;set;}

    public MyProperty<int> SomeOtherProperty { get; set; }
    //public List<MyPropertyBase> MyDataPoints { get; set; }
    public List<Admin_Fee> Admin_Fee 
     {
         get{return _Admin_Fee;}
         set{}
     }
}

【问题讨论】:

    标签: c# .net class generics reflection


    【解决方案1】:

    您可以在Type 上使用GetProperty,然后在PropertyInfo 实例上使用SetValue。根据您的描述,我认为您想要这样的东西:

    void Main()
    {
        BE be  = new BE();
        SetMyPropertyValue("RFID", be, 2);
        SetMyPropertyValue("CUSIP", be, "hello, world");
    
        Console.WriteLine(be.RFID.PropertyValue);
        Console.WriteLine(be.CUSIP.PropertyValue);
    }
    
    private void SetMyPropertyValue(string propertyName, object instance, object valueToSet) 
    {
        Type be = instance.GetType();
        Type valueType = valueToSet.GetType();
        Type typeToSet = typeof(MyProperty<>).MakeGenericType(valueType);
        object value = Activator.CreateInstance(typeToSet,valueToSet);
    
        var prop = be.GetProperty(propertyName);
        prop.SetValue(instance, value, null);
    }
    

    【讨论】:

    • 我试图按照您的建议分配值 string strproname = "FUND_CITY"; System.Reflection.PropertyInfo proInfo =objBe.GetType().GetProperty(strproname); MyProperty propVal =new MyProperty("Mark"); proInfo.SetValue(objBe, propVal, null);但是在运行时我们不能创建 propVal,因为我们不能在运行时输入值。
    • 感谢您的建议。我试图实现代码,但我得到空异常 var prop = be.GetProperty(propertyName).
    • 这个建议看起来很棒。看起来它对我有用。非常感谢。但是需要更多的增强。我们可以将值设置为 be.rfid=2,我们还希望设置 Be.rfid.startoffset=1500 和 be.RFID.EndOffset=1502。如果类型是公共列表 Admin_Fee 这样的集合,那么我们还需要为 类型的每个属性设置值。
    • 我已接受答案。抱歉,我错过了接受帮助的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多