2011-08-17 72 views
2

我有一个扩展方法,像这样的:如何绕过指定通用参数类型的需要?

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

其实我可以用我的代码是这样的:

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

,但我想并不需要指定第二个泛型参数类型:

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

有没有办法在C#3.5中做到这一点?

+0

根据您所提供的代码,我可以看到你需要将TY作为模板参数或将参数传递给您的扩展方法。 – ioWint

回答

2

C#不支持部分泛型推理。如果编译器无法确定您必须自己提供所有类型的所有类型。

+0

感谢您的回复。我意识到我不需要编译时参数的类型,所以我用<表达式>替换了表达式>,它对我的​​使用非常有效。 – Soath

0

你可以做这样的事情:

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

然后,你应该能够只写它像这样:

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

?我不明白。我需要看看一个属性是否绑定了一个属性。在你建议我的最后一行中,没有def。对于TX,这是我想要在属性中寻找的属性: 'Assert.IsTrue(attributes.Any(a => a is TX));' – Soath

+0

对不起,我忘了在方法中指定属性。一秒钟... – Tejs

+0

更新了新的方法和类 – Tejs

相关问题