C#构造函数链接 - 更改执行顺序

Sea*_*rle 6 c# constructor constructor-chaining

我想知道在C#中链接构造函数时如何更改执行顺序.我见过的唯一方法需要在当前构造函数之外首先调用链式构造函数.

具体来说,请参考以下示例:

public class Foo {
  private static Dictionary<string, Thing> ThingCache = new Dictionary<string, Thing>();
  private Thing myThing;

  public Foo(string name) {
    doSomeStuff();
    if (ThingCache.ContainsKey(name)) {
      myThing = ThingCache[name];
    } else {
      myThing = ExternalStaticFactory.GetThing(name);
      ThingCache.Add(name, myThing);
    }
    doSomeOtherStuff();
  }

  public Foo(Thing tmpThing) {
    doSomeStuff();
    myThing = tmpThing;
    doSomeOtherStuff();
  }
}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我希望通过这样做来减少代码重复(请注意,我承认在这个人为的示例中,没有保存太多代码,但我正在使用可以获得更多好处的代码.为了清楚起见,我使用此示例):

public class Foo {
  private static Dictionary<string, Thing> ThingCache = new Dictionary<string, Thing>();
  private Thing myThing;

  public Foo(string name) {
    if (ThingCache.ContainsKey(name)) {
      this(ThingCache[name]);
    } else {
      this(ExternalStaticFactory.GetThing(name));
      ThingCache.Add(name, myThing);
    }
  }

  public Foo(Thing tmpThing) {
    doSomeStuff();
    myThing = tmpThing;
    doSomeOtherStuff();
  }
}
Run Code Online (Sandbox Code Playgroud)

这在VB .Net中是可能的,但C#不允许我在另一个构造函数的中间调用构造函数 - 仅在开始时使用Foo():this()语法.

所以我的问题是,在链接构造函数时如何控制构造函数调用的顺序,而不是使用冒号语法,而冒号语法只能先调用其他构造函数?

Erg*_*wun 8

您不能在其他构造函数中调用构造函数.构造函数只能将另一个构造函数链接到它之前直接调用.

但是,要解决您的特定问题,您可以创建一个私有构造函数,它可以接受两种类型的参数,并让您的两个原始构造函数都只是链接这个,为缺少的参数传递null.

这比调用私有初始化方法更有优势,它可以很好地与readonly字段一起使用(即,如果myThingreadonly字段,它仍然有效):

public class Foo
{
    private static Dictionary<string, Thing> ThingCache =
        new Dictionary<string, Thing>();
    private Thing myThing;

    public Foo(string name)
        : this(null, name)
    {
    }

    public Foo(Thing tmpThing)
        : this(tmpThing, null)
    {
    }

    private Foo(Thing tmpThing, string name)
    {
        if (tmpThing == null && name == null)
        {
            throw new System.ArgumentException(
                "Either tmpThing or name must be non-null.");
        }

        doSomeStuff();
        if (tmpThing != null)
        {
            myThing = tmpThing;
        }
        else
        {
            if (ThingCache.ContainsKey(name))
            {
                myThing = ThingCache[name];
            }
            else
            {
                myThing = ExternalStaticFactory.GetThing(name);
                ThingCache.Add(name, myThing);
            }
        }
        doSomeOtherStuff();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是C#4.0,还可以使用命名参数或可选参数:

http://msdn.microsoft.com/en-us/library/dd264739.aspx


Eri*_*ert 7

我想知道在C#中链接构造函数时如何更改执行顺序.

你没有.C#中没有这样的功能.

已经存在一种以任意顺序调用任意代码的机制:制作一堆方法并按照您喜欢的顺序调用它们.

这是我关于这个主题的文章更详细的说明.

http://blogs.msdn.com/b/ericlippert/archive/2010/01/28/calling-constructors-in-arbitrary-places.aspx

如果构造函数链接设计原则的主题感兴趣,那么您可能也想阅读

http://blogs.msdn.com/b/ericlippert/archive/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one.aspx

http://blogs.msdn.com/b/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx