Unity的类型实例创建

Unity提供了四个配置节来完成类型示例的创建。使用示例类型如下:

复制代码
public interface ILogger
{
  void Write(String text);
  void WriteLine(String text);
}

public sealed class MyLogger : ILogger
{
  public MyLogger(String path)
  {

  }

  public Int32 FileSize { get; set; }

  public void Initialize(Int32 capacity)
  {

  }

  #region ILogger Members

  public void Write(String text)
  {
    throw new NotImplementedException();
  }

  public void WriteLine(String text)
  {
    throw new NotImplementedException();
  }

  #endregion
}
复制代码

1、lifetime,管理类型实例的生命周期。Unity默认提供了几种实现,比如常用的singleton(单例)、perthread(ThreadStatic)等。

<register type=”UnityTest2.ILogger, UnityTest2″ mapTo=”UnityTest2.MyLogger, UnityTest2″>
  <lifetime type=”perthread” />
</register>

开发人员可以通过继承于LifetimeManager自定义生命周期管理。

2、constructor,指定构造函数。比如MyLogger提供了一个参数的构造函数,参数名称为path:

<register type=”UnityTest2.ILogger, UnityTest2″ mapTo=”UnityTest2.MyLogger, UnityTest2″>
  <lifetime type=”perthread” />
  <constructor>
    <param name=”path” value=”D:\” />
  </constructor>
</register>

3、property,当类型实例构造函数执行完后,Unity会根据property的配置初始化对应的值。

<register type=”UnityTest2.ILogger, UnityTest2″ mapTo=”UnityTest2.MyLogger, UnityTest2″>
  <lifetime type=”perthread” />
  <constructor>
    <param name=”path” value=”1″ />
  </constructor>
  <property name=”FileSize” value=”10″ />
</register>

4、method,当类型实例构造函数、属性赋值完成后,Unity会根据method调用不同的函数进行初始化。

复制代码
<register type=”UnityTest2.ILogger, UnityTest2″ mapTo=”UnityTest2.MyLogger, UnityTest2″>
  <lifetime type=”perthread” />
  <constructor>
    <param name=”path” value=”1″ />
  </constructor>
  <property name=”FileSize” value=”10″ />
  <method name=”Initialize”>
    <param name=”capacity” value=”10″ />
  </method>
</register>
复制代码

constructor的param、property、method都允许定义多个。

posted @   junchu25  阅读(1999)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示