Call a universal extension method without specifying the number of types

Here is a snippet of the class that I use to test type extension methods:

class Something
{
  [StringLength(100, MinimumLength = 1, ErrorMessage = "Must have between 1 and 100 characters")]
  public string SomePublicString { get; set; }
}

I have the following extension method:

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();
  }
}

Usage in unit test:

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");

This returns a passing test (using FluentAssertions).

However, I would like to get the GetCustomAttribute () method call on line 2 before the following:

var actual = something.GetCustomAttribute<StringLengthAttribute>(x => x.SomePublicString);

Is it possible? Am I missing something? Maybe I'm in a caffeine crash. :(

+5
source share
2 answers

No, you either need to specify all type arguments, or none of them. There is no "partial" type output.

, , , , , , , - . , , :

something.GetPropertyAttributes(x => x.SomePublicString)
         .FirstAttribute<StringLengthAttribute>();

T TProperty - IEnumerable<Attribute> FirstAttribute OfType/FirstOrDefault. ( , FirstAttribute, , OfType FirstOrDefault .)

+7

, , , .

:

  • .

  • , . ( , , , .)

  • , , - .

+3

All Articles