我有一个像这样的扩展方法:
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 中执行此操作?
最佳答案
C# 不支持部分泛型推断。如果编译器无法确定您必须自己提供的所有类型。
关于c# - 如何绕过指定通用参数类型的需要?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7097329/