前提・実現したいこと
C#の定数について教えてください。
発生している問題・エラーメッセージ
定数に、string.Formatした文字列を設定したところ、
constに割り当てられた式は定数でなければなりません。
とエラーになりました。
該当のソースコード
C#
1 [MaxLength(30, ErrorMessage = "タイトルは30文字以内で入力してください。")] 2 public string Title { get; set; } 3 4 [MaxLength(100, ErrorMessage = "内容は100文字以内で入力してください。")] 5 public string Contents { get; set; }
これを下記のようにしたい。
c#
1 static int length = 30; 2 static string title = "タイトル"; 3 static string errormessage = string.Format("{0}は{1}文字以内で入力してください。", title, length); 4 [MaxLength(length, ErrorMessage = errormessage)] 5 [Display(Name = title)] 6 7 static int length2 = 100; 8 static string title2 = "内容"; 9 static string errormessage2 = string.Format("{0}は{1}文字以内で入力してください。", title2, length2); 10 [MaxLength(length2, ErrorMessage = errormessage2)] 11 public string Contents { get; set; }
試したこと
C#
1 const int length = 30; 2 const string consttitle = "タイトル"; 3 const string errormessage = string.Format("{0}は{1}文字以内で入力してください。", consttitle, length); 4 [MaxLength(length, ErrorMessage = consterrormessage)] 5 public string Title { get; set; }
これだと、
属性引数は、定数式、typeof式、または属性パラメーター形の配列の作成式でなければなりません。 constに割り当てられた式は定数でなければなりません。
とエラーがふたつです。
補足情報(FW/ツールのバージョンなど)
Visual Studio 2017 Pro
回答3件
あなたの回答
tips
プレビュー