本文介绍了懒< T>实施和.NET泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找方法做延迟初始化,发现 延迟< T> 包含在.NET 4中。

I was looking for ways to do lazy initialization and found Lazy<T> which is included in .NET 4.

我在想我自己的滚动实施的延迟&LT; T&GT; 的.NET 3.5(用一个简单的多线程的政策),我碰到了下面的问题

I was thinking of rolling my own implementation of Lazy<T> for .NET 3.5 (with a simpler multi-thread policy), and I bumped into the following problem:

懒人有两种基本类型的构造函数:

Lazy has basically two types of constructors:

class Lazy<T> {

    public Lazy(){...} // ctor #1

它使用T的默认构造函数用于创建T的实例,以及

which uses T's default constructor for creating an instance of T, and

    public Lazy(Func<T> func){...} // ctor #2

这让来电者决定如何T的实例被创建。

which lets the caller decide how the instance of T is created.

现在这里有一个问题:

如果我想编译时检查的第一个构造函数我会加限制

If I want compile-time checking for the 1st ctor I will add a restriction

class Lazy<T> where T: new() {...}

在一流水平。这将允许我使用新T()来创建一个实例;但是这个限制不是必须的第二构造函数,更糟的是,它也限制了I型可以使用(对那些与一默认构造函数)

at the class level. This will allow me to use new T() to create an instance; but this restriction is not necessary for the 2nd ctor, and worse, it also restricts the types I can use (to those with a default ctor)

如果我希望能够使用任何类型的第二构造函数,我将不设置任何限制,并在第一构造函数会使用反射来确保 T 确实有一个默认的构造函数。然而这种方法,就会缺乏编译时检查,如果第一个构造函数使用了错误类型只会引发运行时异常。

If I want to be able to use any type with the 2nd ctor, I will not set any restriction, and in the 1st ctor will use reflection to make sure T does have a default ctor. This approach, however, will lack the compile-time check, and will only throw a runtime exception if the 1st ctor is used with the wrong type.

我的问题是:我可以得到两全其美?

My question is: Can I get the best of both worlds?

在理想情况下,我想获得的编译时间检查每个使用构造函数#1,但同时能够使用构造函数#2为不具有默认构造函数的类型。

Ideally, I would like to get the compile-time check for every use of ctor #1, but at the same time be able to use ctor #2 for types that don't have a default ctor.

如何Microsoft实现做到这一点? (我不容易访问到.NET 4路信号源或DLL)。

How does the Microsoft implementation do this? (I don't readily have access to the .NET 4 sources or dlls).

编辑:(后反射镜 - 荷兰国际集团的MS组装)

(After "Reflector-ing" the MS assembly)

我检查的参考实现,并没有做编译时检查。
它使用过程中伴随着的运行时异常反射为默认构造函数的情况下,如果事情变坏。

I checked the reference implementation and it doesn't do compile-time checks.
It uses reflection for the 'default ctor' case, of course accompanied by the runtime exception if things go bad.

推荐答案

我想到了内置的实现仅仅使用 Activator.CreateInstance&LT; T&GT; 的简单性。我能想到这个作弊的清洁方法是使用一个单独的工厂:

I expect the inbuilt implementation simply uses Activator.CreateInstance<T> for simplicity. The cleanest way I can think of cheating this is with a separate factory:

// non-generic factory class with generic methods
public static class Lazy {
    public static Lazy<T> Create<T>() where T : new() {
        return Create<T>(() => new T());
    }
    public static Lazy<T> Create<T>(Func<T> ctor) { ... }
}
public class Lazy<T> { ... }

这篇关于懒&LT; T&GT;实施和.NET泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:07