c# – Unity解析多个类

前端之家收集整理的这篇文章主要介绍了c# – Unity解析多个类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何让microsoft unity为给定的接口类型“构造”一个​​类的列表.

非常简单的例子:

List<IShippingCalculation> list = new List<IShippingCalculation>();
  list.Add(new NewYorkShippingCalculation());
  list.Add(new FloridaShippingCalculation());
  list.Add(new AlaskShippingCalculation());

  //Not What I want
  public void calcship(List<IShippingCalculation> list)
  {
    var info = new ShippingInfo(list);
    info.CalculateShippingAmount(State.Alaska)
  }

  //Somehow in unity,must i do this for all the concrete classes? 
  //how does it know to give a list.
  Container.RegisterType<IShippingInfo,new AlaskaShippingCalculation()>();??

  //What I want
  public void calcship(IShippingInfo info)
  {
    info.CalculateShippingAmount(State.Alaska)
  }

谢谢!

解决方法

如果您使用的是Unity 2,则可以使用ResolveAll< T>
Container.RegisterType<IShippingInfo,FloridaShippingCalculation>("Florida");
Container.RegisterType<IShippingInfo,NewYorkShippingCalculation>("NewYork");
Container.RegisterType<IShippingInfo,AlaskaShippingCalculation>("Alaska");

IEnumerable<IShippingInfo> infos = Container.ResolveAll<IShippingInfo>();

你必须给每个注册一个名字,因为ResolveAll只会返回命名注册.

原文链接:https://www.f2er.com/csharp/96170.html

猜你在找的C#相关文章