C# 某些属性的GetPropertyInfo失败
我已经搜索和尝试了几个小时了,但现在对我来说没有意义。 基本上,我在一个.NET4.5项目中有两个类库 在使用反射时,我可以访问一些属性,但不能访问所有属性,而且我看不到自己的错误 库A定义了数据结构:C# 某些属性的GetPropertyInfo失败,c#,C#,我已经搜索和尝试了几个小时了,但现在对我来说没有意义。 基本上,我在一个.NET4.5项目中有两个类库 在使用反射时,我可以访问一些属性,但不能访问所有属性,而且我看不到自己的错误 库A定义了数据结构: public class HeaderRow { public string Format { get; set; } public Int32 Version { get; set; } = 0; public CustomEnum
public class HeaderRow
{
public string Format { get; set; }
public Int32 Version { get; set; } = 0;
public CustomEnum Datacategory { get; set; }
public Custom2Enum FormatnameEnum { get; set; }
public int Formatversion { get; set; }
public UInt64 CreatedAt { get; set; }
public string Origin {get; set;}
}
我想在库2中填入以下代码:
protected PropertyInfo FindPropertyInfo(object o, string propertyName)
{
Type objektTyp = o.GetType();
PropertyInfo info = objektTyp.GetProperty(propertyName,BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
return info;
}
public override void FillValueToColumns(object o, string property, string value)
{
FindPropertyInfo(o,property).SetValue(o,value);
}
我可以访问:
格式而非来源
创建数据,但不创建格式版本
我看不到我的自定义枚举
对于所有我看不到的内容,“info”为空。
非常感谢您的帮助。
谢谢,您将无法使用SetValue将字符串分配给例如int。为此,您需要将FillValueToColumns重载为int(例如)作为最后一个参数,否则您需要获得类型转换器,如下所示:
PropertyInfo PropertyInfo=FindPropertyInfo(o,propertyName);
TypeConverter-TypeConverter=TypeDescriptor.GetConverter(propertyInfo.PropertyType);
object v=typeConverter.ConvertFrom(null,CultureInfo.CurrentCulture,值??);
if(v==null&&propertyInfo.PropertyType.IsValueType&&Nullable.GetUnderlineType(propertyInfo.PropertyType)==null){
抛出新的InvalidCastException(“将null赋值给不可为null的值类型!”);
}
propertyInfo.SetValue(对象,v);
sjb感谢您。我的错。很抱歉 确实是一个命名问题 通过复制和粘贴,我在字符串属性中创建了空格。所以我在寻找 “起源” 而不是 “起源”
->删除多余的空格解决了问题。您确定输入了正确的属性名称字符串吗?您确定库2引用的是库A的最新版本吗?可能是大小写问题
BindingFlags。IgnoreCase
您还试图在非字符串属性上设置字符串值。@Crowcoder,是的,我很确定。两个库都在一个解决方案中。我基本上一次复制并粘贴了所有属性(因为它们来自我必须实现的接口描述),最后我创建了一个测试属性,如果我在调试器中展开“objektyp”,它就会显示出来。对不起,我不知道为什么格式化不起作用。剪切并粘贴到VS以阅读它,我猜。谢谢。我没有背景问题。因为“getPropertyInfo”是我使用的基类的一部分。基类只需找到属性。我使用一组格式化程序类来确定设置值的责任链的正确类型。基本上,我尝试采用(SuperCSV Idea:)建议使用“nameof”来避免此类问题。