C#   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c#泛型类无法获取属性值大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
使用c#反射得到&设置通用对象内的通用字段的值.但我找不到任何方法来获得这些字段的属性值.下面的代码示例:

public class Foo<T>
{
   public bool IsUpdated { get; set; } 
}

public abstract class ValueObjec<T>
{
   public string InnerValue { get; set; } 
}

public class ItemList: ValueObject<ItemList>
{
   public Foo<string> FirstName;

   public Foo<string> LastName;
}

问题
在行(*)处获取“null”项.

itemField.GetType()始终返回System.Reflection.RtFieldInfo类型,但不返回Foo类型.

我已经尝试过使用itemField.FieldType.GetProperty(“IsUpdated”),它在返回正确的属性时起作用.但抛出错误“对象与目标类型不匹配”.每当调用GetValue()方法
itemField.FieldType.GetProperty(“IsUpdated”).GetValue(itemField,null)

如果得到任何人的帮助,我们将非常感激!

var itemList = new ItemList();
foreach (var itemField in itemList.GetType().GetFields())
{
    var isUpdated = "false";
    var isUpdatedProp = itemField.GetType().GetProperty("IsUpdated"); // (*) return null from here
    if (isUpdatedProp != null)
    {
        isUpdated = isUpdatedProp.GetValue(itemField,null).ToString();
        if (isUpdated == "false") isUpdatedProp.SetValue(itemField,"true");
    }
}

foreach (var itemField in itemList.GetType().GetFields())
        {
            var isUpdated = "false";
            var isUpdatedProp = itemField.FieldType.GetProperty("IsUpdated");
            if (isUpdatedProp != null)
            {
                isUpdated = isUpdatedProp.GetValue(itemField,null).ToString(); (*) // throw error "Object does not match target type"
                if (isUpdated == "false") isUpdatedProp.SetValue(itemField,"true");
            }
        }

解决方法

让我们一次解开这一件事:

var isUpdatedProp = itemField.GetType().GetProperty("IsUpdated");

你永远不需要在成员上使用.GetType();你想要.FieldType或.PropertyType(对于属性).并且名字很棒:

var isUpdatedProp = itemField.FieldType.GetProperty(nameof(Foo<string>.IsUpdated));

(这里的字符串是假的)

然后:

isUpdated = isUpdatedProp.GetValue(itemField,null).ToString();

itemField不是你的对象 – 这就是该对象上itemField的值给你的东西.所以通过;如果可能的话,将结果视为布尔值:

var isUpdated = false;
object foo = itemField.GetValue(itemList);
...
isUpdated = (bool)isUpdatedProp.GetValue(foo,null);

最后:

if (isUpdated == "false") isUpdatedProp.SetValue(itemField,"true");

对象再次是itemList,属性不是字符串

if (!isUpdated) isUpdatedProp.SetValue(foo,true);

如果你制作Foo< T>会更容易. :IFoo,其中IFoo是非通用接口:

interface IFoo { bool IsUpdated {get; set; } }

然后它变成:

var foo = (IFoo)itemField.GetValue(itemList);
if(!foo.IsUpdated) foo.IsUpdated = true;

最后,请注意,如果您没有为它们指定任何内容,FirstName和LastName将为null.

大佬总结

以上是大佬教程为你收集整理的c#泛型类无法获取属性值全部内容,希望文章能够帮你解决c#泛型类无法获取属性值所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: