gpt4 book ai didi

c# - 如何绕过指定通用参数类型的需要?

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:18 25 4
gpt4 key购买 nike

我有一个像这样的扩展方法:

      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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com