C# C语言中的字段和属性对缩短#

C# C语言中的字段和属性对缩短#,c#,unity3d,C#,Unity3d,我的代码中分散了以下几个属性: private Animator _anim; public Animator anim { get { if (_anim == null) { _anim = GetComponent<Animator> (); } return _anim; } set { _anim = value;

我的代码中分散了以下几个属性:

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 GetComponent(ref _anim)); }
    set { _anim = value; } 
}

基本上,没有-没有任何东西可以让您使用自动实现的属性和“一点”自定义代码。您可以将代码缩短为:

public Animator Animator
{
    get { return _anim ?? (_anim = GetComponent<Animator>()); }
    set { _anim = value; } 
}
其中
GetComponent
类似于:

public T GetComponent(ref T existingValue)
{
    return existingValue ?? (existingValue = GetComponent<T>());
}
public T GetComponent(ref T existingValue)
{
返回existingValue??(existingValue=GetComponent());
}
如果您不喜欢使用具有如下副作用的null coalescing操作符,可以将其重写为:

public T GetComponent(ref T existingValue)
{
    if (existingValue == null)
    {
        existingValue = GetComponent<T>();
    }
    return existingValue;
}
public T GetComponent(ref T existingValue)
{
if(existingValue==null)
{
existingValue=GetComponent();
}
返回现有值;
}

请注意,这些解决方案都不是线程安全的—就像您的原始代码一样,如果第二个线程在第一个线程通过“IsIt null”检查后将属性设置为null,则该属性可以返回null,这可能不是您的意图。(这甚至没有考虑到涉及的内存模型问题。)根据您希望语义是什么,有多种解决方法。

谢谢您的回答,我会接受的。我总是忘了??。(联合国)幸运的是Unity API是单线程的,所以我不必担心这里的安全性。