我有一个Dictionary<string,string> dictionary
其中键保存属性的名称,值保存相应的值。然后我有许多不同的模型和一个处理这些不同模型的通用类。我正在尝试通过模式匹配来设置相关属性的值(除非有更好的方法?)。
var record = new T();
foreach (var property in ReflectiveOps.Properties(record))
{
if (dictionary.ContainsKey(property.Name))
{
switch ...???
我尝试切换 property.PropertyType
然后case int
和case int i
但这没有用。我可以做 if(property.PropertyType.Name == "int"{...}
- 这样可行。这可以通过开关来完成吗?
最佳答案
处理运行时键入的属性的一种方法是根据属性类型构建操作字典。换句话说,而不是写
// This does not work, but imagine for a moment that it does:
switch (property.PropertyType) {
case typeof(int): DoSomethingWithInt(property, val, obj); break;
case typeof(string): DoSomethingWithString(property, val, obj); break;
case typeof(long): DoSomethingWithLong(property, val, obj); break;
default: throw new InvalidOperationException($"Unsupported type: {property.PropertyType.Name}");
}
写下:
var opByType = new Dictionary<Type,Action<PropertyInfo,string,object>> {
{ typeof(int), (p, s, o) => DoSomethingWithInt(property, val, obj) }
, { typeof(string), (p, s, o) => DoSomethingWithString(property, val, obj) }
, { typeof(long), (p, s, o) => DoSomethingWithLong(property, val, obj) }
};
opByType
字典中的操作对应于未编译的 switch
相应 case 内的代码。
现在您可以使用 property.PropertyType
检索该类型的操作,并调用该操作。
关于C# 通用类的模式匹配属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44677247/