C# 通用类的模式匹配属性?

标签 c# generics properties switch-statement

我有一个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"{...} - 这样可行。这可以通过开关来完成吗?

最佳答案

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

// 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/

相关文章:

c# - 无法安装 MSVS 2010 C# Express - 先决条件 x64 不安装

c# - 使用 Xamarin 的 iOS 应用的安装日期

typescript - 如何基于通用类型 "T"初始化 TypeORM 存储库?

java - 泛型的协方差

java - 在 Spring 测试中加载文件

c# - 将动态加载类型传递给 SomeFunction<T>

c# - 我是否需要将数据库事务与 c# TableAdapters 一起使用?

c# - new() 的通用类型约束和抽象基类

javascript - 如何制作具有属性的 JavaScript 数组?

delphi - 它是否违反了接口(interface)属性访问器公开的封装?