2015-09-04 26 views
1

......畢竟,這實際上可能不是一個變異問題。當我編譯代碼時,Visual Studio就會給我下面的錯誤:尋找有關變化問題的解釋

Type of conditional expression cannot be determined because there is no implicit conversion between 'ClassA' and 'ClassB'

我在這裏這個錯誤讀了,它肯定聽起來這是不可能的,我可以用抽象類作爲接口等,合同使用派生類代替它們的基類。爲了使事情變得更簡單,我編寫了一些模擬我實際代碼關係的測試類。請考慮以下幾點:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace AbstractClassImplicitConversion { 
    class Program { 
     static void Main(string[] args) { 
      StartClass temp = new StartClass(); 
     } 
    } 

    public class StartClass 
    { 
     public AbstractClass _ac { get; private set; } 

     public StartClass() 
     { 
      bool which = true; 
      // this block will compile 
      /* 
      if(which) 
       _ac = new DerivedClass1(); 
      else 
       _ac = new DerivedClass2(); 
      */ 
      // this block will not compile 
      _ac = which ? new DerivedClass1() : new DerivedClass2(); 
     } 
    } 

    public interface SomeInterface 
    { 
     void SiFoo(); 
    } 

    public abstract class InnerAbstractClass 
    { 
     public abstract void IacFoo(); 
    } 

    public abstract class AbstractClass : InnerAbstractClass, SomeInterface 
    { 
     public override void IacFoo() { 

     } 

     public void SiFoo() { 

     } 

     public abstract void OverrideMe(); 
     public abstract void OverrideMeToo<T>(); 
    } 

    public class DerivedClass1 : AbstractClass 
    { 
     public override void OverrideMe() {} 
     public override void OverrideMeToo<T>() {} 
    } 

    public class DerivedClass2 : AbstractClass 
    { 
     private int _blah; 
     public override void OverrideMe() {} 
     public override void OverrideMeToo<T>() {} 
    } 
} 

的問題是與線:

_ac = which ? new DerivedClass1() : new DerivedClass2(); 

如果我使用內聯如果,我會得到可怕的編譯器錯誤。但是,如果我改用這個:

if(which) 
    _ac = new DerivedClass1(); 
else 
    _ac = new DerivedClass2(); 

我的代碼編譯得很好。

任何人都可以解釋是什麼原因造成的?我一直認爲這兩者是等同的。謝謝!

+1

你可以通過轉換到基類來解決這個問題。 – crashmstr

+0

雖然這是一個很好看的問題,但我沒有看到它與一旦你可能已經看過的情況有什麼不同。版本「爲什麼兩個兄弟派生類之間沒有隱式轉換」可能是很好的非重複選擇,但我懷疑你已經知道了答案。還有其他答案,比如http://stackoverflow.com/a/202296/477420,它可能更好,但所有內容基本上與Daniel A. White的好答案一樣。 –

+0

附註:考慮更新你的帖子,題目是關於「三元/條件運算符」 - 所以它可能是未來搜索的好路標。 –

回答

7

這僅僅是語言標準的定義方式:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

DerivedClass1DerivedClass2之間不存在隱式轉換 - 它只能通過存在的基類。運算符的規範沒有說它在賦值時會查看結果值類型,因此編譯器正在執行它設計的任務。

來源:https://msdn.microsoft.com/en-us/library/ty67wk28.aspx

+0

感謝您的鏈接! – Dave

+0

@Dave隨時! –

1

我認爲你需要更改代碼如下得到你要尋找的效果:

_ac = which ? (new DerivedClass1() as AbstractClass) : (new DerivedClass2() as AbstractClass); 

希望這有助於!

+2

'as'在這裏是過度殺傷。改爲使用一元'(Type)'。 –