我有一個擴展方法,像這樣的:如何繞過指定通用參數類型的需要?
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中做到這一點?
根據您所提供的代碼,我可以看到你需要將TY作爲模板參數或將參數傳遞給您的擴展方法。 – ioWint