是否可以在C#7.0中使用ref returns功能定义一个通用函数,该函数可以在对象的两个实例中进行字段的比较和更新?我在想像这样的东西:
Is it possible to use the ref returns feature in C# 7.0 define a generic function that can do both comparison and update of a field in two instances of an Object? I am imagining something like this:
void UpdateIfChanged<TClass, TField>(TClass c1, TClass c2, Func<TClass, TField> getter) { if (!getter(c1).Equals(getter(c2)) { getter(c1) = getter(c2); } }示例用法:
Thing thing1 = new Thing(field1: 0, field2: "foo"); Thing thing2 = new Thing(field1: -5, field2: "foo"); UpdateIfChanged(thing1, thing2, (Thing t) => ref t.field1); UpdateIfChanged(thing1, thing2, (Thing t) => ref t.field2);是否有任何方法可以指定Func类型或任何通用类型限制,从而通过要求getter返回引用来使其生效?我尝试了Func<TClass, ref TField>,但是它似乎不是有效的语法.
Is there any way to specify a Func type or any kind of generic type restriction that would make this valid by requiring that getter return a reference? I tried Func<TClass, ref TField>, but it doesn't appear to be valid syntax.
推荐答案您将无法使用Func,因为它不会通过引用返回结果.您需要创建一个使用ref返回的新委托:
You won't be able to use Func, because it doesn't return the result by reference. You'll need to create a new delegate that uses a ref return:
public delegate ref TResult RefReturningFunc<TParameter, TResult>(TParameter param);然后更改您的函数以使用该委托就足以使其正常工作:
Then changing your function to use that delegate is enough for it to work:
public static void UpdateIfChanged<TClass, TField>(TClass c1, TClass c2, RefReturningFunc<TClass, TField> getter) { if (!getter(c1).Equals(getter(c2))) { getter(c1) = getter(c2); } }请注意,属性不能通过引用返回.您可以通过引用或任何其他变量返回 field ,但是属性不是变量.
Note that a property cannot be returned by reference. You could return a field by reference, or any other variable, but a property is not a variable.
更多推荐
C#7.0中的泛型函数和ref返回
发布评论