【问题标题】:Passing type <T>传递类型 <T>
【发布时间】:2012-09-15 06:41:11
【问题描述】:

我在第三方组件中有一个方法,可以像下面的代码一样调用:

ICustomer log = Axis.GetInstance<ICustomer>();

由于我不想将上述第三方组件直接暴露给所有调用者,我决定创建一个调用第三方“Axis.GetInstance()”的包装方法,我的问题是如何传递类型 T并调用泛型方法中的方法

调用代码:

var result = Util.MyCustomWrapper<ICustomer>();


public class Util
{
  public static T MyCustomWrapper<T>()
  {

    1.call Axis.GetInstance<T>(); // **how to pass the type T**
    2.return T

  }
}

【问题讨论】:

  • return Axis.GetInstance&lt;T&gt;();“不起作用”怎么办?

标签: c# generics


【解决方案1】:

方法可以像你写的那样调用:

public static T MyCustomWrapper<T>()
{
    return Axis.GetInstance<T>();
}

【讨论】:

  • 当我这样写时出现此错误“类型'T'必须是引用类型才能使用”
  • @TiffanyHarry 那么你必须在你的方法中添加一个类型约束:where T : class
  • @TiffanyHarry:啊哈,这可能意味着Axis.GetInstance 的通用参数定义了一个generic constraint,它要求类型参数是引用类型。在 T 参数上定义相同(或更严格的)约束:MyCustomWrapper&lt;T&gt;() where T : class
  • @TiffanyHarry 这就是为什么你应该发布实际错误而不是“它不起作用”
  • @phoog,@ O.R Mapper:有一个类型约束..现在它正在工作
【解决方案2】:
public class Util
{
    public static T MyCustomWrapper<T>()
    {
        T customer = Axis.GetInstance<T>(); 
        return customer;
    }
}

加上其他要编译的类型

public interface ICustomer { }
public class Axis
{
    public static T GetInstance<T>() 
    {
        throw new NotImplementedException();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-04
    • 2021-06-23
    • 2020-01-13
    • 2018-03-26
    • 1970-01-01
    • 2021-10-23
    • 2011-05-23
    相关资源
    最近更新 更多