【问题标题】:c# Pattern Matching Properties of a Generic Class?c#泛型类的模式匹配属性?
【发布时间】:2017-06-21 13:15:44
【问题描述】:

我有一个Dictionary<string,string> dictionary,其中的键包含属性的名称,值对应的值。然后我有许多不同的模型和一个处理这些不同模型的通用类。我正在尝试通过模式匹配来设置相关属性的值(除非有更好的方法?)。

var record = new T();

foreach (var property in ReflectiveOps.Properties(record))
{
    if (dictionary.ContainsKey(property.Name))
    {
         switch ...???

我尝试切换property.PropertyType,然后切换case intcase int i,但没有奏效。我可以做一个if(property.PropertyType.Name == "int"{...} - 那行得通。这可以通过开关完成吗?

【问题讨论】:

  • property.PropertyType == typeof(int) 会更好
  • @PatrickHofman:是的,但这似乎也只适用于if..then 语句。如果我将它放入案例中,我会收到一个错误,即预期值为常量。
  • @PatrickHofman 但一个很好的建议...(错误捕获 atm,并看到名称“int32”恰好与“int”不同,但与您的 typeof 相同:-)

标签: c# generics properties switch-statement


【解决方案1】:

处理在运行时键入的属性的一种方法是构建基于属性类型的操作字典。换句话说,而不是写

// 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 对应案例中的代码。

现在您可以使用property.PropertyType 检索该类型的操作,并调用该操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 2019-06-03
    • 2019-08-04
    • 1970-01-01
    • 2016-09-04
    • 2011-10-25
    相关资源
    最近更新 更多