Avoid General Arguments

I have the following extension method, which claims that the property (Id) contains the specified attribute (TV):

public static void ShouldHave<T, TV, TT>(this T obj, Expression<Func<T, TT>> exp) {...}

The method can be called as follows:

MyDto myDto = new MyDto();
myDto.ShouldHave<MyDto, RequiredAttribute, int>(x => x.Id);

It compiles just fine. I was wondering if it is possible to remove T and TT from the method signature. T, because ShouldHave is called on T, so it is not necessary to specify it explicitly. And TT is the type of property referenced by the expression (x.Id).

+3
source share
3 answers

Automatic output of type arguments only works if no common arguments are specified in the method call. Ie this:

myDto.ShouldHave<, RequiredAttribute, >(x => x.Id);

Invalid syntax. You can either "all or nothing."

, T TT, , TV, - . , :

public static void ShouldHave<T, TT>(this T obj, 
                                     Expression<Func<T, TT>> exp, 
                                     Type attribute) {...}

(, ShouldHave).

:

MyDto myDto = new MyDto();
myDto.ShouldHave(x => x.Id, typeof(RequiredAttribute));
+1

:

public static void ShouldHave<T, TT>(this T obj, Expression<Func<T, TT>> exp)
{...}

MyDto myDto = new MyDto();
myDto.ShouldHave(x => x.Id);

TV, . , .

+2

:

public static void ShouldHave<TV>(this object obj, Expression<Func<object, object>> exp) {...}

, exp , cast to object. :

Expression realExp = ((UnaryExpression) exp).Operand;

. , .

0

All Articles