我有一个像这样的扩展方法:
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 :(得分:2)
C#不支持部分通用推理。如果编译器无法确定您必须自己提供的所有类型。
答案 1 :(得分: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>();