我的很多类都是不同类型的知名但无序对象的容器,例如容器可能如下所示:
public class Container
{
public A A { get; private set; }
public B B { get; private set; }
public C C { get; private set; }
public bool StoreIfKnown(object o)
{
// TODO...
}
}
因此,如果o
是类型A
,则应将其存储在属性A
中,键入属性等等。B
B
在 F# 中,该StoreIfKnown
方法可以编写如下(请原谅语法错误,我的 F# 不是很好而且很生锈):
match o with
| ?: A a -> A <- a; true
| ?: B b -> B <- b; true
| ?: C c -> C <- c; true
| _ -> false
但在 C# 中,唯一的方法似乎是相当冗长:
if (o is A)
{
this.A = (A)o;
return true;
}
if (o is B)
{
this.B = (B)o;
return true;
}
// etc.
return false;
我可以使用as
关键字来避免测试/演员模式,这会更快,但更冗长。
在 C# 中有什么优雅的方法可以做到这一点吗?