实现一个" LazyProperty"类 - 这是个好主意吗? [英] Implementing a "LazyProperty" class - is this a good idea?
问题描述
我经常发现自己写的是懒洋洋地评估一个属性。是这样的:
I often find myself writing a property that is evaluated lazily. Something like:
if (backingField == null)
backingField = SomeOperation();
return backingField;
这是没有太大的code,但是它可以重复了很多,如果你有很多的属性。
It is not much code, but it does get repeated a lot if you have a lot of properties.
我想定义一个类LazyProperty:
I am thinking about defining a class called LazyProperty:
public class LazyProperty<T>
{
private readonly Func<T> getter;
public LazyProperty(Func<T> getter)
{
this.getter = getter;
}
private bool loaded = false;
private T propertyValue;
public T Value
{
get
{
if (!loaded)
{
propertyValue = getter();
loaded = true;
}
return propertyValue;
}
}
public static implicit operator T(LazyProperty<T> rhs)
{
return rhs.Value;
}
}
这使我能够初始化一个领域是这样的:
This would enable me to initialize a field like this:
first = new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value });
和随后的属性的本体可以下降到
And then the body of the property could be reduced to:
public HeavyObject First { get { return first; } }
这将使用最多的公司,因为它会进入一个共同的类库通过我们的大部分产品共享。
This would be used by most of the company, since it would go into a common class library shared by most of our products.
我不能确定这是否是一个好主意或没有。我认为解决方案有一些优点,如:
I cannot decide whether this is a good idea or not. I think the solutions has some pros, like:
- 在减code
- prettier code
在下跌,这将是很难看code和确定到底发生了什么 - 特别是如果开发人员不熟悉LazyProperty类。
On the downside, it would be harder to look at the code and determine exactly what happens - especially if a developer is not familiar with the LazyProperty class.
你怎么看?这是一个好主意,或者我应该放弃呢? 还有,就是隐含的运营商是个好主意,或者你会preFER使用Value属性明确,如果你要使用这个类呢?
What do you think ? Is this a good idea or should I abandon it ? Also, is the implicit operator a good idea, or would you prefer to use the Value property explicitly if you should be using this class ?
意见和建议,欢迎: - )
Opinions and suggestions are welcomed :-)
推荐答案
只是过于迂腐:
您提出的解决方案,以避免重复code:
Your proposed solution to avoid repeating code:
private LazyProperty<HeavyObject> first =
new LazyProperty<HeavyObject>(() => new HeavyObject { MyProperty = Value });
public HeavyObject First {
get {
return first;
}
}
实际上比你不想重复code更多的字符:
Is actually more characters than the code that you did not want to repeat:
private HeavyObject first;
public HeavyObject First {
get {
if (first == null) first = new HeavyObject { MyProperty = Value };
return first;
}
}
除此之外,我认为隐式转换取得了code很难理解。我也不会想到,一个方法,只返回第一个,实际上最终创建一个HeavyObject。我想至少已经下降了隐式转换和从属性返回first.Value。
Apart from that, I think that the implicit cast made the code very hard to understand. I would not have guessed that a method that simply returns first, actually end up creating a HeavyObject. I would at least have dropped the implicit conversion and returned first.Value from the property.
这篇关于实现一个&QUOT; LazyProperty&QUOT;类 - 这是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!