문제

In JavaScript we can OR two objects/properties like this:-

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

also

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

Can we OR C# class objects?

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

var temp = sc1 || sc2;

Edit:-

Not working for me using ??

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();

        }
    }
}

Error:-

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

도움이 되었습니까?

해결책

The null-coalescing operator (??) will do this for you:

var temp = sc1 ?? sc2;

If sc1 is null, temp will be sc2.

다른 팁

If you overwrite the operator for that class, then you can do it and it will do exactly what you want.

s. here how to do it: http://msdn.microsoft.com/en-us/library/aa288467(v=vs.71).aspx

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top