if语句中的赋值 [英] Assignment in an if statement

查看:151
本文介绍了if语句中的赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动物 Animal 及其子类 Dog
我经常发现自己编写以下代码:

I have a class Animal, and its subclass Dog. I often find myself coding the following lines:

if (animal is Dog)
{
    Dog dog = animal as Dog;    
    dog.Name;    
    ... 
}

对于变量动物;

For the variable Animal animal;.

是否有一些语法可以让我编写如下内容:

Is there some syntax that allows me to write something like:

if (Dog dog = animal as Dog)
{    
    dog.Name;    
    ... 
}


推荐答案

下面的答案是几年前写的,并随着时间的推移而更新。从C#7开始,您可以使用模式匹配:

The answer below was written years ago and updated over time. As of C# 7, you can use pattern matching:

if (animal is Dog dog)
{
    // Use dog here
}

请注意, dog 仍在 if 语句之后,但未明确赋值。

Note that dog is still in scope after the if statement, but isn't definitely assigned.

不,没有。

Dog dog = animal as Dog;
if (dog != null)
{
    // Use dog
}

鉴于 后面的几乎总是 以此方式使用,因此对于有一个一次性执行两个部分的运算符可能更有意义。如果模式匹配提案<,此代码当前不在C#6中,但可能是C#7的一部分。 / a>已实现。

Given that "as followed by if" is almost always used this way, it might make more sense for there to be an operator which performs both parts in one go. This isn't currently in C# 6, but may be part of C# 7, if the pattern matching proposal is implemented.

问题是您不能在声明一个变量> if 语句 1 。我能想到的最接近的方法是:

The problem is that you can't declare a variable in the condition part of an if statement1. The closest approach I can think of is this:

// EVIL EVIL EVIL. DO NOT USE.
for (Dog dog = animal as Dog; dog != null; dog = null)
{
    ...
}

这真是令人讨厌的 ...(我刚刚尝试过,它确实有效。但是请,请不要哦,您当然可以使用 var 声明 dog 。)

That's just nasty... (I've just tried it, and it does work. But please, please don't do this. Oh, and you can declare dog using var of course.)

当然,您可以编写扩展方法:

Of course you could write an extension method:

public static void AsIf<T>(this object value, Action<T> action) where T : class
{
    T t = value as T;
    if (t != null)
    {
        action(t);
    }
}

然后用以下方式调用它:

Then call it with:

animal.AsIf<Dog>(dog => {
    // Use dog in here
});

或者,您可以将两者结合:

Alternatively, you could combine the two:

public static void AsIf<T>(this object value, Action<T> action) where T : class
{
    // EVIL EVIL EVIL
    for (var t = value as T; t != null; t = null)
    {
        action(t);
    }
}

您也可以使用不带lambda表达式的扩展方法

You can also use an extension method without a lambda expression in a cleaner way than the for loop:

public static IEnumerable<T> AsOrEmpty(this object value)
{
    T t = value as T;
    if (t != null)
    {
        yield return t;
    }
}

然后:

foreach (Dog dog in animal.AsOrEmpty<Dog>())
{
    // use dog
}






1 您可以 if 语句中分配值,尽管我很少这样做。但是,这与声明变量不同。尽管在读取数据流时,我在期间进行操作并不是非常。例如:


1 You can assign values in if statements, although I rarely do so. That's not the same as declaring variables though. It's not terribly unusual for me to do it in a while though when reading streams of data. For example:

string line;
while ((line = reader.ReadLine()) != null)
{
    ...
}

这些天,我通常更喜欢使用包装器,这样我就可以使用 foreach(...中的字符串行)但我将以上内容视为一种惯用的模式。在条件内具有副作用通常 并不好,但是替代方法通常涉及代码重复,并且当您知道这种模式时,很容易就正确了。

These days I normally prefer to use a wrapper which lets me use foreach (string line in ...) but I view the above as a pretty idiomatic pattern. It's usually not nice to have side-effects within a condition, but the alternatives usually involve code duplication, and when you know this pattern it's easy to get right.

这篇关于if语句中的赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆