MVC および LINQ のエキスパートの皆様、こんにちは。
次のようなモデルがあります。
public class SomeClass : IValidatableObject
{
public string SomeString { get; set; }
public string SomeString2 { get; set; }
public int SomeInteger { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
//... IF there is some error...THEN
yield return new ValidationResult("Some Error Message.", GetFieldNames(() => new []{ this.SomeString }));
}
}
ご覧のとおり、式を受け取る GetFieldNames を呼び出して、式のメンバーを文字列配列として返します。最近読んだ本によると、エラーをフィールドにリンクする方法は、次のように文字列として渡すことです。
yield return new ValidationResult("Some Error Message.", new []{ "SomeString" }));
しかし、私は強く型付けされたかったので、私が書いた方法は次のとおりです。
public static string[] GetFieldNames(Expression<Func<object[]>> exp)
{
//Build a string that will in the end look like this: field1,field2,field3
//Then we split(',') it into an array and return that string array.
string fieldnames = "";
MemberExpression body = exp.Body as MemberExpression;
if (body == null)
{
NewArrayExpression ubody = (NewArrayExpression)exp.Body;
foreach(MemberExpression exp2 in ubody.Expressions)
{
fieldnames += exp2.Member.Name + ",";
}
fieldnames = fieldnames.TrimEnd(',');
}
if(fieldnames.Length > 0)
return fieldnames.Split(',');
else
return new string[]{};
}
現在の使用状況:
GetFieldNames(() => new[] { this.SomeString , this.SomeString2 });
出力:
{ "SomeString" , "SomeString2" }
これはうまくいきます。
問題は、次のように使用すると、エラーが発生することです (コンパイル時)。
GetFieldNames(() => new[] { this.SomeString , this.SomeInteger });
エラー:
No best type found for implicitly-typed array
私の希望する出力:
{ "SomeString" , "SomeInteger" }
int は複合型ではないため、オブジェクトの配列を渡すことができません。
int
andを使用して関数に式配列を渡すにはどうすればよいstring
ですか?