- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个通用函数,可以使用反射从 DataRow
创建对象。我正在使用此函数从 Access 数据库导入表:
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var prop in properties)
{
try
{
if (prop.PropertyType.IsEnum)
prop.SetValue(item, row[prop.Name], null); // what to do??
else
prop.SetValue(item, row[prop.Name], null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, string.Format("failed to assign {0} a value of {1}", prop.Name, row[prop.Name]));
}
}
return item;
}
我遇到的问题是属性类型是 enum
。我试过使用 Enum.Parse
,但没有成功(我无法编译任何东西)。
有什么方法可以使用我的函数将 row[prop.Name]
表示的对象转换为正确的 enum
吗?或者我是否需要为我定义的 enum
编写一个特殊的转换函数。
编辑:我得到了
"the type or namespace prop could not be found. Are you missing an assembly directive or reference" compile error for the following:
var val = (prop.PropertyType)Enum.Parse(typeof(prop.PropertyType), row[prop.Name].ToString());
最佳答案
The reason for the type or namespace prop could not be found
你得到的异常是因为你不能以这种方式转换为类型 (prop.PropertyType)Enum.Parse(typeof (prop.PropertyType)
- 您只能在编译时知道类型的情况下执行此操作 - (SomeEnum)Enum.Parse(typeof(SomeEnum)
。
正确的做法是在设置属性值之前获取枚举值:
prop.SetValue(item, Enum.ToObject(prop.PropertyType, row[prop.Name]), null);
关于c# - 将 PropertyInfo.PropertyType 转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28502604/
我有这样的类型定义: type Blah = { fields: { value: string }[] } 我们在这里看到字段是一堆数组条目。我想通过 $PropertyT
我有这样的类型定义: type Blah = { fields: { value: string }[] } 我们在这里看到字段是一堆数组条目。我想通过 $PropertyT
我怎样才能让它工作? switch(property.PropertyType){ case typeof(Boolean): //doStuff break;
这个问题在这里已经有了答案: C#: Getting size of a value-type variable at runtime? (8 个答案) 关闭 9 年前。 我有一个函数可以确定记录值
我有以下用 EF 生成的类“schakeling”,表示数据库表“schakeling”。在数据库中,'id' 是主键,'plc_id' 是外键。 public partial class schak
我正在尝试通过反序列化 json 来创建属性的新实例字符串。调用JsonConvert.DeserializeObject(string)当我明确说明 T 的类型时有效: var foo = Json
我有一个通用函数,可以使用反射从 DataRow 创建对象。我正在使用此函数从 Access 数据库导入表: private static T CreateItemFromRow(DataRow ro
我想使用 PropertyType 返回的类型来创建类型化函数。我发现这个相似 using type returned by Type.GetType() in c#但这提到了如何创建一个列表,但没有
我有如下类: public class SampleClassToTest { public static Fake SomeMethod(string parameter) {
我的问题是:怎样才能使 PropertyInfo.GetValue(object, null); 转换为 PropertyType 的返回值,而不是返回对象。 我试过 Convert.ChangeTy
我正在使用这两个库: Unity-SerializableDictionary: https://github.com/starikcetin/Unity-SerializableDictionary
我想使用反射获取属性类型。这是我的代码 var properties = type.GetProperties(); foreach (var propertyInfo in properties)
我正在遍历对象并初始化该对象的所有属性。首先,对象的类型即类被放置在我的同一个项目中并且工作正常。现在,我将该类移到另一个项目中,但仍然使用 AssemblyName.Namespace.Class
我只需要显示名称在必填字段列表中的属性。 我正在尝试做这样的事情,但是 p.PropertyType.Name == x 不正确: Pricing pricing = new Pricing(); T
我只需要显示名称在必填字段列表中的属性。 我正在尝试做这样的事情,但是 p.PropertyType.Name == x 不正确: Pricing pricing = new Pricing(); T
我是一名优秀的程序员,十分优秀!