相关疑难解决方法(0)

通过使用不同属性类型的反射设置对象的属性

我使用反射来填充对象的属性.

这些属性有不同的类型:String,Nullable(double)和Nullable(long)(不知道如何在这里转义尖括号......).这些属性的值来自(字符串,对象)对的字典.

因此,例如我的类具有以下属性:

string Description { get; set; } 
Nullable<long> Id { get; set; }
Nullable<double> MaxPower { get; set; }
Run Code Online (Sandbox Code Playgroud)

(实际上有大约十几个属性),字典将有<"描述","描述">,<"Id",123456>,<"MaxPower",20000>等条目

现在我使用类似以下内容来设置值:

foreach (PropertyInfo info in this.GetType().GetProperties())
{
    if (info.CanRead)
    {
         object thisPropertyValue = dictionary[info.Name];

         if (thisPropertyValue != null && info.CanWrite)
         {
             Type propertyType = info.PropertyType;

             if (propertyType == typeof(String))
             {
                 info.SetValue(this, Convert.ToString(thisPropertyValue), null);
             }
             else if (propertyType == typeof(Nullable<double>))
             {
                 info.SetValue(this, Convert.ToDouble(thisPropertyValue), null);
             }
             else if (propertyType == typeof(Nullable<long>))
             {
                 info.SetValue(this, Convert.ToInt64(thisPropertyValue), null);
             }
             else
             {
                 throw new …
Run Code Online (Sandbox Code Playgroud)

c# reflection runtime properties

6
推荐指数
1
解决办法
6209
查看次数

枚举 GetCustomAttributes 不显示任何内容

在这个简单的类中,我尝试覆盖 ToString() 以显示所有自定义属性。

public class TryMe
{
    public TryMe(int id, List<String> tests)
    {
        ID = id;
        Tests = tests;
    }
    public int ID { get; set; }
    public List<String> Tests { get; set; }

    public override string ToString()
    {
        string me = "";
        var attributes = this.GetType().GetCustomAttributes();

        foreach (var attribute in attributes)
        {
            me = me + attribute.ToString() + ",";
        }
        return me;
    }
}
Run Code Online (Sandbox Code Playgroud)

它不显示任何值或错误。

不是ID和Tests自定义属性吗?如果类变大,是否有任何简单的枚举?

c#

0
推荐指数
1
解决办法
33
查看次数

标签 统计

c# ×2

properties ×1

reflection ×1

runtime ×1