在C#中,如果对象属于某种类型,我有时必须做某事.
例如,
if (x is A)
{
// do stuff but have to cast using (x as A)
}
Run Code Online (Sandbox Code Playgroud)
如果在if街区内,我们可以x像使用它一样真的很好A,因为它不可能是其他任何东西!
例如,
if (x is A)
{
(x as A).foo(); // redundant and verbose
x.foo(); // A contains a method called foo
}
Run Code Online (Sandbox Code Playgroud)
编译器是不是很聪明,不知道这个或是否有任何可能的技巧来获得类似的行为
Dlang能否有效地做类似的事情?
顺便说一句,我不是在寻找动态.只是尝试编写更简洁的代码.显然我可以做var y = x as A;而y不是用X.
在D中,您通常采用的模式是:
if(auto a = cast(A) your_obj) {
// use a in here, it is now of type A
// and will correctly check the class type
}
Run Code Online (Sandbox Code Playgroud)