简体   繁体   中英

if (x is A) { // use x as A

In C# I sometimes have to do something if the object is of some type.

eg,

if (x is A)
{
    // do stuff but have to cast using (x as A)
}

What would be really nice if inside the if block, we could just use x as if it were an A , since it can't be anything else!

eg,

if (x is A)
{
    (x as A).foo(); // redundant and verbose
    x.foo();   // A contains a method called foo
}

Is the compiler just not smart enough to know this or is there any possible tricks to get similar behavior

Can the Dlang effectively do something similar?

BTW, I'm not looking for dynamic. Just trying to write less verbose code. Obviously I can do var y = x as A; and use y instead of X .

In D, the pattern you'd usually do is:

if(auto a = cast(A) your_obj) {
    // use a in here, it is now of type A
    // and will correctly check the class type
}

For one statement (or chain-able calls) you can use (x as A)?.Foo() in C# 6.0+ as shown in Is there an "opposite" to the null coalescing operator? (…in any language?) .

There is no multiple statements version in the C# language, so if you want you'll need to write your own. Ie using Action for body of the if statement:

  void IfIsType<T>(object x, Action<T> action)
  {
     if (x is T)
          action((T)x);
  }

object s = "aaa";
IfIsType<string>(s, x => Console.WriteLine(x.IndexOf("a")));

I believe this is a feature is under consideration for C# 7. See the Roslyn issue for documentation, specifically 5.1 Type Pattern:

The type pattern is useful for performing runtime type tests of reference types, and replaces the idiom

var v = expr as Type;
if (v != null) { // code using v }

With the slightly more concise

if (expr is Type v) { // code using v }`

As for Dlang, I would reference their if statement syntax documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM