c# - 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。第二种解决方案意味着弱类型问题和无用的装箱/拆箱。
是否有第三种更清洁的解决方案来拥有“可空或不可空”的泛型参数?
解决方案
推荐阅读
- visual-studio - “System.NullReferenceException”类型的第一次机会异常
- php - 如何确保每个事件只能通过 codeigniter 中的 role_id 查看(只有超级管理员可以查看所有列表)?
- php - 如何将数据传递给外部程序并取回结果
- istio - Istio 服务到服务流量加密
- json - 如何将用户评论容器添加到 Listview Flutter
- android - 测试错误 - NoClassDefFoundError:解析失败:Lorg/hamcrest/Matchers
- javascript - Angular - 如何处理后端到前端的命名约定?
- swift - 如何在 SwiftUI 中为网格布局创建自定义大小的正方形
- express - 如何使用 JPG 数据字符串在 Express 中响应?
- c - 交叉编译库链接