Problems with adding a `lazy` keyword to C#

2019-03-09 07:09发布

I would love to write code like this:

class Zebra
{
    public lazy int StripeCount
    {
        get { return ExpensiveCountingMethodThatReallyOnlyNeedsToBeRunOnce(); }
    }
}

EDIT: Why? I think it looks better than:

class Zebra
{
    private Lazy<int> _StripeCount;

    public Zebra()
    {
        this._StripeCount = new Lazy(() => ExpensiveCountingMethodThatReallyOnlyNeedsToBeRunOnce());
    }

    public lazy int StripeCount
    {
        get { return this._StripeCount.Value; }
    }
}

The first time you call the property, it would run the code in the get block, and afterward would just return the value from it.

My questions:

  1. What costs would be involved with adding this kind of keyword to the library?
  2. What situations would this be problematic in?
  3. Would you find this useful?

I'm not starting a crusade to get this into the next version of the library, but I am curious what kind of considerations a feature such as this should have to go through.

7条回答
ゆ 、 Hurt°
2楼-- · 2019-03-09 08:02

The system library already has a class that does what you want: System.Lazy<T>

I'm sure it could be integrated into the language, but as Eric Lippert will tell you adding features to a language is not something to take lightly. Many things have to be considered, and the benefit/cost ratio needs to be very good. Since System.Lazy already handles this pretty well, I doubt we will see this anytime soon.

查看更多
登录 后发表回答