【问题标题】:How to cast a class to an interface using generics in c#?如何在 C# 中使用泛型将类转换为接口?
【发布时间】:2013-04-11 18:45:56
【问题描述】:

我有这个界面:

public interface IRepository<T>
{
    List<T> List();
    T Get(int Id);        
    bool Add(T entity);
    bool Update(T entity);
}

我有这门课:

public class Customer<T> : IRepository<Entities.Customer>
{
   public Entities.Customer Get(int Id)
   {
      var c = new Entities.Customer();
      return c;
   }

   //continue...
}

如何将泛型类转换为这样的泛型接口:

//Other method
public IRepositorio<T> DoStuff<T>(int Id)
{  
   var a = (IRepository<Entities.Customer>)Activator.CreateInstance(typeof(T)); // ok               
   var b = (IRepository<T>)Activator.CreateInstance(typeof(T)); // Exception: unable to cast       

   return object; // an object
}

我从这个 MCV 控制器调用:

  public ActionResult Home()
  {
     var repo = new Repository();
     repo.DoStuff<Customer<Entities.Custormer>>(10);

     return View();
  }

我的受孕还好吗?没有动态这可能吗?

【问题讨论】:

    标签: asp.net-mvc class c#-4.0 generics interface


    【解决方案1】:

    根据提供的代码,我尝试了以下编译成功

    public class Entities {
        public class Customer {
        }
    }
    
    public interface IRepository<T> {
        T Get(int Id);
    }
    
    public class Customer<T> : IRepository<Entities.Customer> {
        public Entities.Customer Get(int Id) {
            var cliente = new Entities.Customer();
            return cliente;
        }
    }
    
    public class foo {
    
        public static IRepository<T> DoStuff<T>(int Id) {
            var a = (IRepository<Entities.Customer>)Activator.CreateInstance(typeof(T));
            var b = (IRepository<T>)Activator.CreateInstance(typeof(T));
    
            return b; // an object
        }
    
    }
    

    但是,我不确定 T 是什么意思。当我跑步和打电话时

    foo.DoStuff<Entities.Customer>(0);
    

    然后我在var a 行上得到一个运行时错误,因为类Entities.Customer 没有实现接口IRepository&lt;T&gt;。如果我打电话

    foo.DoStuff<Customer<Entities.Customer>>(0);
    

    然后我在 'var b' 行得到运行时错误,因为类 Customer&lt;Entities.Customer&gt; 实现 IRepository&lt;Entities.Customer&gt; 而不是 IRepository&lt;Customer&lt;Entities.Customer&gt;&gt;

    这两个例外都是正确的,所以希望问题的作者可以从这个答案中找出问题所在。

    【讨论】:

    • 也为我编译,但在运行时引发“无法转换异常”。
    • 那你能发布产生运行时错误的最小代码吗?
    • 我重新起草了我的答案。这能回答你的问题吗?
    【解决方案2】:

    Activator.CreateInstance(typeof(T)); - 这将为您创建 T 的新实例,在您的示例中为 Entities.Customer,但看起来您想要创建 Customer&lt;Entities.Customer&gt; 的实例。

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 2016-10-20
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      相关资源
      最近更新 更多