【问题标题】:Prompt user for values for all public properties on a class提示用户输入类上所有公共属性的值
【发布时间】:2023-03-15 16:11:01
【问题描述】:

C# 使得get all public properties get a property value by name 变得相对容易。

但是设置属性值呢?对于一个简单的测试应用程序,我希望能够做类似这个伪代码的事情,它枚举类实例上的公共属性,提示用户输入值,并根据这些值设置属性 - 根据需要从输入字符串转换为属性类型:

for(Property p in typeof(instance))
{
 s = ReadLine("Enter the value for {p.Name}, type {p.Type}");
 SetPropertyValue(instance,p.Name, p.Type.parse(s));
}

我遇到的使通用实用程序方法SetPropertyValue 变得困难的主要问题是Parse 并不总是存在。它适用于大多数基本类型,但当然不适用于 string 或更高级别的类型。

我不介意它在不支持的类型上失败,因为我的使用基本上是intshortstringbyte 等,但是我如何使用反射来敲击某些东西准备好控制台模式测试应用了吗?

【问题讨论】:

  • 您可以使用TypeConverterTypeDescriptor 来解决这个问题。也许System.Convert 在这里也很有用。

标签: c# reflection


【解决方案1】:

@Mr.男孩 - 类似的东西?:

    ...
    public class Class1
    {
            public int IntProperty { get; set; }
            public string StringProperty { get; set; }
    }
    ...
    var instance1 = new Class1();
    var typeofclass1 = typeof(Class1);
    System.Reflection.PropertyInfo[] listProperty = instance1.GetType().GetProperties();
    var somevalue = "1234";
    foreach(var p in listProperty)
    {
            p.SetValue(instance1, Convert.ChangeType(somevalue, p.PropertyType), null);
    }

【讨论】:

  • typeofproperty 似乎命名错误。
  • @NetMage - 为什么?为我编译就好了。
  • 因为typeofproperty 实际上正是变量不是。它是p.NameClass1 属性的PropertyInfo,所以也许propertyInfoForNamepiFromClass1 会更好。
  • 我开始编辑并发现了第二个问题-您已经有p-您为什么还要查找它?只需使用p
猜你喜欢
  • 2012-04-18
  • 2012-11-08
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 2022-07-15
  • 2014-03-14
  • 2011-02-26
相关资源
最近更新 更多