Dưới đây là một đoạn của một lớp tôi sử dụng cho phương pháp mở rộng thử nghiệm Loại:Gọi một phương pháp khuyến nông chung mà không chỉ định như nhiều loại
class Something
{
[StringLength(100, MinimumLength = 1, ErrorMessage = "Must have between 1 and 100 characters")]
public string SomePublicString { get; set; }
}
tôi có phương pháp mở rộng sau:
public static class TypeExtensions
{
public static TAttributeType GetCustomAttribute<T, TAttributeType, TProperty>(this T value, Expression<Func<T, TProperty>> propertyLambda, bool inherit = false)
{
var type = typeof(T);
var member = (MemberExpression)propertyLambda.Body;
var propertyInfo = (PropertyInfo)member.Member;
var customAttributes = propertyInfo.GetCustomAttributes(typeof(TAttributeType), inherit);
return customAttributes.OfType<TAttributeType>().FirstOrDefault();
}
}
Cách sử dụng trong thử nghiệm đơn vị:
1: var something = new Something();
2: var actual = something.GetCustomAttribute<Something, StringLengthAttribute, string>(x => x.SomePublicString);
3: actual.MinimumLength.Should().Be(1);
4: actual.MaximumLength.Should().Be(100);
5: actual.ErrorMessage.Should().Be("Must have between 1 and 100 characters");
Trả lại này một bài kiểm tra vượt qua (sử dụng FluentAssertions).
Tuy nhiên, tôi muốn để có được các cuộc gọi phương pháp để GetCustomAttribute() trong dòng 2 xuống như sau:
var actual = something.GetCustomAttribute<StringLengthAttribute>(x => x.SomePublicString);
Đây có phải là có thể? Tui bỏ lỡ điều gì vậy? Có lẽ tôi đang gặp tai nạn caffeine. :(
Huzzah cho Nguyên tắc chịu trách nhiệm duy nhất. – StriplingWarrior
Cảm ơn. Ban đầu tôi đã có một cái gì đó giống như mẫu mã của bạn, phá vỡ sự phản ánh 'PropertyInfo', phản xạ thuộc tính tùy chỉnh, và cuối cùng, loại tôi muốn, nhưng đã hy vọng cho một cái gì đó ... leaner. :-) –
@Dan, tôi thường nghe rằng khiếu nại áp dụng cho giải pháp này và chưa bao giờ thực sự hiểu được nó đến từ đâu.Có vẻ khá nạc với tôi (đối với người tiêu dùng). –