c#中的字段和属性对缩短
本文关键字:属性 字段 | 更新日期: 2023-09-27 18:09:16
我的代码中有几个这样的属性:
private Animator _anim;
public Animator anim
{
get
{
if (_anim == null)
{
_anim = GetComponent<Animator> ();
}
return _anim;
}
set
{
_anim = value;
}
}
我想知道是否有可能缩短这个语义,或者通过像这样的自定义字段声明:
public autogetprop Animator anim;
或通过如下属性:
[AutoGetProp]
public Animator anim;
基本上,没有任何东西可以让您使用"一点点"自定义代码自动实现属性。您可以将代码缩短为:
public Animator Animator
{
get { return _anim ?? (_anim = GetComponent<Animator>()); }
set { _anim = value; }
}
或者你可以写一个带ref参数的GetComponent
方法,并像这样使用它:
public Animator Animator
{
get { return GetComponent(ref _anim)); }
set { _anim = value; }
}
其中GetComponent
应该是这样的:
public T GetComponent(ref T existingValue)
{
return existingValue ?? (existingValue = GetComponent<T>());
}
如果您不喜欢使用具有此类副作用的空合并操作符,您可以将其重写为:
public T GetComponent(ref T existingValue)
{
if (existingValue == null)
{
existingValue = GetComponent<T>();
}
return existingValue;
}
请注意,这些解决方案都不是线程安全的-就像您的原始代码一样,如果第二个线程在之后将属性设置为null ,第一个线程已经通过了"是否为空"检查,该属性可以返回null,这可能不是意图。(这还没有考虑到所涉及的内存模型问题。)根据您想要的语义,有多种方法可以解决这个问题。