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

标签 c# types extension-methods generics

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

      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/

相关文章:

c# - 什么是 Environment.FailFast?

Scala 多类型模式匹配

.net - 最快的 .Net 和 SQL 数据类型

python-3.x - Mypy 报告与重写方法不兼容的父类(super class)型错误

c# - 扩展方法何时中断?

c# - 使用 IsInDateTimeRange 扩展 IQueryable

c# - 为什么我在此代码上得到 CS1056 意外字符 ''

c# - 为什么TextBox Border Color在WPF中坚持不变?

c# - 使用 asp.net c# 从 ListView 中的选定项目中获取值

c# - 如何为类型创建扩展方法