2011-07-01 7 views
2
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class User 
    { 
     public int? Age { get; set; } 
     public int? ID { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      User user = new User(); 
      user.Age = null;  // no warning or error 
      user.ID = (int?)null; // no warning or error 

      string result = string.Empty; 
      User user2 = new User 
          { 
       Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result), 
       // Error 1 Type of conditional expression cannot be determined 
       // because there is no implicit conversion between '<null>' and 'int' 
       // ConsoleApplication1\ConsoleApplication1\Program.cs 23 71 ConsoleApplication1 

       ID = string.IsNullOrEmpty(result) ? (int?)null : Int32.Parse(result) // // no warning or error 
          }; 
     } 
    } 
} 

質問:オブジェクトイニシャライザを使用する場合はなぜuse(int?)nullですか?

次の行が動作しないのはなぜ?

Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result) 

//修正1は

Age = string.IsNullOrEmpty(result) ? (int?) null : Int32.Parse(result) 

なぜ次の行の作品ですか!

user.Age = null;  // no warning or error 
+0

http://stackoverflow.com/questions/1171717を参照してください。 –

答えて

3
Age = string.IsNullOrEmpty(result) ? null : Int32.Parse(result) 

は動作しません。

コンパイラは、string.IsNullOrEmpty(result) ? null : Int32.Parse(result)の種類を特定できません。

最初に参照型であることを示すnullがあり、互換性がないと思われる値型のintがあります。 intからint?までの暗黙のキャスト演算子を持つ型が存在するという事実は、コンパイラによって推論されません。

理論的にはそれを理解するのに十分な情報があるかもしれませんが、コンパイラはより洗練されたものにする必要があります。

2

C#はすべての式に型が必要であることを強制するためです。コンパイラは、動作していない行の三項式の型を判別できません。

6

これは、3項演算子が戻り値の型を同じ型にする必要があるからです。

第1のケースでは、「null」は参照型(intだけでなく)のnullになり、キャストする必要のあるコンパイラに明示的にすることができます。

そうしないと、あなたは明らかにビットcuckoooある

string x = null; 
Age = string.IsNullOrEmpty(result) ? x: Int32.Parse(result) 

を持つことができます。

2

? :インラインif演算子は、2つの引数がnullintであるため、どの型を返すかわかりません。 intはnullになることはありませんので、コンパイラは?:によって返される型を解決できません。 string.IsNullOrEmpty(result) ? null : Int32.Parse(result)Age =部分とは別に評価されるため

関連する問題