开发者

How to bypass the need of specifing a generic parameter type?

开发者 https://www.devze.com 2023-03-28 23:52 出处:网络
I have an extension method like this one : public static void ImplementsAttribute<TX, TY>(this Expression<Func<TY>> expression)

I have an extension method like this one :

      public static void ImplementsAttribute<TX, TY>(this Expression<Func<TY>> expression) 
     where TX : Coupling.PropertiesMergerAttribute
  {
     var memberExpression 开发者_高级运维= expression.Body as MemberExpression;
     var name = MetaHelper.GetPropertyName(expression);
     var property = memberExpression.Expression.Type.GetProperty(name);
     var attributes = property.GetCustomAttributes(true);
     Assert.IsTrue(attributes.Any(a => a is TX));
  }

I can actually use my code like this :

     Expression<Func<String>> nameProperty = () => new ImprovisedExplosiveXML().Name;
     nameProperty.ImplementsAttribute<Coupling.UnresolvablePropertiesMergerAttribute, String>();

but I would like to not need to specify the second generic parameter type :

     Expression<Func<String>> nameProperty = () => new ImprovisedExplosiveXML().Name;
     nameProperty.ImplementsAttribute<Coupling.UnresolvablePropertiesMergerAttribute>();

Is there a way of doing this in C# 3.5 ?


C# does not support partial generic inference. If the compiler can't determine all the types you have to supply them all yourself.


You can do something like this:

public class AttributeTester
{
    public Attribute[] Attributes { get; set; }

    public void ImplementsAttribute<TAttType>()
    {
         Assert.IsTrue(Attributes.Any(x => x is TAttType));
    }
}

public static void ForProperty<TType, TProperty>(this TType obj, Expression<Func<TType, TProperty>> expression)
{
     var memberExpression = expression.Body as MemberExpression;
     var name = MetaHelper.GetPropertyName(expression);
     var property = memberExpression.Expression.Type.GetProperty(name);
     return new AttributeTester { Attributes = property.GetCustomAttributes(true) };
}

Then, you should be able to just write it like so:

new ImproveisedExplosiveXML().ForProperty(x => x.Name).ImplementsAttribute<SomeAttribute>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号