从访问者返回新实例是否存在问题?如果是这样,有更好的方法吗?
public class Person
{
private RecIpDet _ipDet;
public RecIpDet IpDet
{
get
{
if(_ipDet == null)
_ipDet = new RecIpDet();
return _ipDet;
}
}
}
Run Code Online (Sandbox Code Playgroud)
存在问题,因为您从未设置字段,因此每次调用属性时都会返回一个新对象.
您应该设置_ipDet它是否为null,然后返回它.这称为延迟实例化或延迟初始化.
public class Person
{
private RecIpDet _ipDet;
public RecIpDet IpDet
{
get
{
if (_ipDet == null)
{
_ipDet = new RecIpDet();
}
return _ipDet;
}
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,这不是线程安全的,所以如果这是你的一个因素,你需要一个更强大的机制.对于单线程应用程序,这种惰性实例化方法很好.
如果您使用的是.NET 4.0或更高版本,则可以使用Lazy<T>我认为是线程安全的类:
public class Person
{
private Lazy<RecIpDet> _ipDet = new Lazy<RecIpDet>(() => new RecIpDet());
public RecIpDet IpDet
{
get
{
return _ipDet.Value;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
对我们来说,通常的做法是使用:
get
{
return _ipDet ?? (_ipDet = new RecIpDet());
}
Run Code Online (Sandbox Code Playgroud)