C#7.0中的泛型函数和ref返回

编程入门 行业动态 更新时间:2024-10-28 06:32:27
本文介绍了C#7.0中的泛型函数和ref返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在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返回

本文发布于:2023-11-04 10:39:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   ref

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!