gpt4 book ai didi

c# - 字典将字符串映射到属性

转载 作者:太空宇宙 更新时间:2023-11-03 21:26:36 26 4
gpt4 key购买 nike

我有一个类,我想根据一个字符串返回各种属性的值,我可以像这样定义一个属性:

    [FieldName("data_bus")]
public string Databus
{
get { return _record.Databus; }
}

所以我想要一本字典:

private static readonly IDictionary<string, Func<string>> PropertyMap;

这里初始化:

static MyClass()
{
PropertyMap = new Dictionary<string, Func<string>>();

var myType = typeof(ArisingViewModel);

foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetGetMethod() != null)
{
var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();

if (attr == null)
continue;

PropertyInfo info = propertyInfo;
PropertyMap.Add(attr.FieldName, () => info.Name);
// Not sure what I'm doing here.
}
}
}

并以某种方式调用:

   public static object GetPropertyValue(object obj, string field)
{

Func<string> prop;
PropertyMap.TryGetValue(field, out prop);
// return
}

谁能告诉我如何设置它?我不确定我是否正确理解 Func 的工作原理。

最佳答案

您将需要更改您的字典定义,以便该函数将接受该类的一个实例

private static readonly IDictionary<string, Func<ArisingViewModel,string>> PropertyMap;

那么你需要你的静态初始化器是

static MyClass()
{
PropertyMap = new Dictionary<string, Func<ArisingViewModel,string>>();

var myType = typeof(ArisingViewModel);

foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetGetMethod() != null)
{
var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();

if (attr == null)
continue;

PropertyInfo info = propertyInfo;
PropertyMap.Add(attr.FieldName, obj => (string)info.GetValue(obj,null));
}
}
}

public static object GetPropertyValue(ArisingViewModel obj, string field)
{
Func<ArisingViewModel,string> prop;
if (PropertyMap.TryGetValue(field, out prop)) {
return prop(obj);
}
return null; //Return null if no match
}

如果您愿意,您还可以使您的解决方案更通用一些。

public static MyClass<T> {

private static readonly IDictionary<string, Func<T,string>> PropertyMap;


static MyClass()
{
PropertyMap = new Dictionary<string, Func<T,string>>();

var myType = typeof(T);

foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (propertyInfo.GetGetMethod() != null)
{
var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>();

if (attr == null)
continue;

PropertyInfo info = propertyInfo;
PropertyMap.Add(attr.FieldName, obj => (string)info.GetValue(obj,null));
}
}
}

public static object GetPropertyValue(T obj, string field)
{
Func<ArisingViewModel,string> prop;
if (PropertyMap.TryGetValue(field, out prop)) {
return prop(obj);
}
return null; //Return null if no match
}
}

编辑 - 并调用你会做的通用版本

var value = MyClass<ArisingViewModel>.GetPropertyValue(mymodel,"data_bus");

关于c# - 字典将字符串映射到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26628313/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com