条件付きのオペレーターとNullable<value> のか。
-
09-06-2019 - |
質問
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: Convert.ToInt32(employeeNumberTextBox.Text),
私は自分のいいものはこのような形になります。(EmployeeNumber
は Nullable<int>
としてこのプロパティLINQ to SQL dbmlオブジェクトの列でNULL値)。残念ながら、コンパイラを感じることが暗黙的に変換'null'および'int'"ものの種類が有効に割り当て操作をnullable intです。
Null律でオペレーターはかけがえのない存在で調査を実施しているのは、同じくご覧いただけるインライン変換えが起きる。テキスト文字列の場合はnullになります。
私の知るかぎりのことで使用if文および/または割り当て。この特定のケースでは見ることもたかったので使用のオブジェクト初期化子構文では、この課題の初期化ブロック...
誰でも知っていますエレガントな解決方法?
解決
万一問題が発生したので、条件付きのオペレーターなどのように値が使用される高さに加えてこの場合)を決定するタイプの表現だけ、true/falseの値です。この場合、 nullの場合 や Int32, の型が決定できない(実際について詳しい性質を調べることができない Nullable<Int32>).
またこのようになって、キャストの値 Nullable<Int32> 自分の、C#を解決することができるタイプ:
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? (int?)null
: Convert.ToInt32(employeeNumberTextBox.Text),
または
EmployeeNumber =
string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text),
他のヒント
と思いるユーティリティメソッドがこのクリーナーです。
public static class Convert
{
public static T? To<T>(string value, Converter<string, T> converter) where T: struct
{
return string.IsNullOrEmpty(value) ? null : (T?)converter(value);
}
}
その
EmployeeNumber = Convert.To<int>(employeeNumberTextBox.Text, Int32.Parse);
をアレックスの修正及び近位不明な点があれば、ここでお答えいりませんので、予めご TryParse
:
int value;
int? EmployeeNumber = int.TryParse(employeeNumberTextBox.Text, out value)
? (int?)value
: null;
での安全のアフターケアの場合は無効入力として空文字列のシナリオに対するその場合、ユーザの入力のようなもの 1b
ものであると考えられるエラーのページを独自のレンダリングメカニズム例外が発生 Convert.ToInt32(string)
.
できるキャストの出力に変換す:
EmployeeNumber = string.IsNullOrEmpty(employeeNumberTextBox.Text)
? null
: (int?)Convert.ToInt32(employeeNumberTextBox.Text)
//Some operation to populate Posid.I am not interested in zero or null
int? Posid = SvcClient.GetHolidayCount(xDateFrom.Value.Date,xDateTo.Value.Date).Response;
var x1 = (Posid.HasValue && Posid.Value > 0) ? (int?)Posid.Value : null;
編集:概略の説明を記していたの値を取得し Posid
場合は、null以外 int
び値が0より大きい)にvaribale X1
.利用いただ (int?)
月 Posid.Value
の取得を条件としていない従業員に投げ入れコンパイルエラー.ただのストラヴァ工科大学 GetHolidayCount
は WCF
る方法が null
又は番号です。のこ