首页 > 解决方案 > C# 通用参数 - 是否有任何“可空或不可空”约束

问题描述

我经常使用泛型和Expression<Func<object, value>>构建工具来定位对象的属性。我一直在为 C# 的一个非常愚蠢的限制而苦苦挣扎(但也许我不知道正确的解决方案)。

假设我们有这个对象:

class MyObject {
  public int NeverNull { get; set; }
  public int? CanBeNull { get; set; }
}

我希望能够做到这一点:

int? val1 = Foo(o => o.NeverNull);
int? val2 = Foo(o => o.CanBeNull);

我有两个解决方案来做到这一点:

// Solution 1: two overloads
// First overload: for the non-nullable properties
TValue? Foo<TValue>(Expression<Func<MyObject, TValue>> selector)
  where TValue: struct
{ ... }

// Second overload: for the nullable properties
TValue? Foo<TValue>(Expression<Func<MyObject, TValue?>> selector)
  where TValue: struct
{ ... }

// Solution 2: using object
TValue? Foo<TValue>(Expression<Func<MyObject, object>> selector)
  where TValue: struct
{ ... }

第一个解决方案意味着将逻辑加倍,这是meh。第二种解决方案意味着弱类型问题和无用的装箱/拆箱。

是否有第三种更清洁的解决方案来拥有“可空或不可空”的泛型参数?

标签: c#nullablegeneric-constraints

解决方案


推荐阅读