如何在C#中短路'或'分配?

时间:2014-02-24 13:22:09

标签: c# javascript or-operator

在JavaScript中我们可以OR这样的两个对象/属性: -

var myURL = window.URL || window.webkitURL;

function doKey(e) {
    var evt = e || window.event; // compliant with ie6      
    //Code
}

我们可以OR C#类对象吗?

SpecificClass1 sc1 = new SpecificClass1();
SpecificClass2 sc2 = new SpecificClass2();
sc2 = null;

var temp = sc1 || sc2;

修改: -

使用??

不适合我
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MultipleCast
{
    class Program
    {

        public class BaseClass { 
        }
        public class SpecificClass1 : BaseClass
        {
            public string SpecificMethod1()
            {
                return "SpecificMethod1";
            }

        }
        public class SpecificClass2 : BaseClass
        {
            public string SpecificMethod2()
            {
                return "SpecificMethod2";
            }
        }
        public class SpecificClass3 : BaseClass
        {
            public string SpecificMethod3()
            {
                return "SpecificMethod3";
            }
        }

        static void Main(string[] args)
        {

            SpecificClass1 sc1 = new SpecificClass1();
            SpecificClass2 sc2 = new SpecificClass2();
            sc1 = null;

            var temp = sc1 ?? sc2;

            Console.WriteLine(temp);

            Console.Read();

        }
    }
}

错误: -

Operator '??' cannot be applied to operands of type 'MultipleCast.Program.SpecificClass1' and 'MultipleCast.Program.SpecificClass2'

2 个答案:

答案 0 :(得分:6)

null-coalescing operator??)会为您执行此操作:

var temp = sc1 ?? sc2;

如果sc1nulltemp将为sc2

答案 1 :(得分:-2)

如果覆盖该类的运算符,则可以执行此操作 它会完全符合您的要求。

秒。这里怎么做: http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx