gpt4 book ai didi

c# - 模式 : "if (obj is Abc && (obj as Abc) ...)" 的方法

转载 作者:行者123 更新时间:2023-11-30 13:55:50 29 4
gpt4 key购买 nike

这里有两个简单的类:

class Abc { public int x; }
class Bcd { public int y; }

鉴于 objobject 类型,这里有几个测试 AbcBcd 的例子具有某些特征:

if (obj is Abc && (obj as Abc).x > 0 && Math.Pow((obj as Abc).x, 2) > 100)
Console.WriteLine(123);

if (obj is Bcd && (obj as Bcd).y > 0 && Math.Pow((obj as Bcd).y, 2) > 100)
Console.WriteLine(234);

处理这种模式的好方法是什么:

if (obj is Abc && (obj as Abc).SomePropertyOrMethod && ...

一种方法是 Is 扩展方法:

public static bool Is<T>(this object obj, Func<T, bool> pred) where T : class
=> (obj is T) && pred(obj as T);

有了这个,上面的例子可以写成:

if (obj.Is<Abc>(abc => abc.x > 0 && Math.Pow(abc.x, 2) > 100))
Console.WriteLine(123);

if (obj.Is<Bcd>(bcd => bcd.y > 0 && Math.Pow(bcd.y, 2) > 100))
Console.WriteLine(234);

这样,(obj as ...) 表达式就不会重复了。

这种模式还有其他方法吗?

pattern matching proposal它似乎可以很好地处理这个问题(请参阅第 8.1 节)。

最佳答案

我觉得这把一件简单的事情变得复杂了。扩展 object 导致的 namespace 污染也不好。此外,这是对 as 的误用。这应该是一个 throw 转换(例如 ((Abc)obj)),因为我们希望转换总是成功。 throwing cast 有一个断言和一个很好的内置异常。它记录了预期会成功的事实。

另一种方法是声明一个变量:

var abc = obj as Abc;
if (abc != null && abc.x > 0 && Math.Pow(abc.x, 2) > 100)
Console.WriteLine(123);

看起来很简单。我看不出有什么问题。

也就是说,扩展方法方法在您无法轻松声明变量的地方很有用,例如在某些查询或深层嵌套的表达式中。这通常是不可取的,但有时会发生。

关于c# - 模式 : "if (obj is Abc && (obj as Abc) ...)" 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31776304/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com