c# - 具有复杂逻辑的多个构造函数

标签 c# .net

在 C# 中,如果你有多个构造函数,你可以这样做:

public MyClass(Guid inputId, string inputName){
    // do something
}

public MyClass(Guid inputId): this(inputId, "foo") {}

这个想法当然是代码重用。但是,当需要一些复杂的逻辑时,最好的方法是什么?假设我想要这个构造函数:

public MyClass(MyOtherClass inputObject)
{
    Guid inputId = inputObject.ID;
    MyThirdClass mc = inputObject.CreateHelper();
    string inputText = mc.Text;
    mc.Dispose();
    // Need to call the main Constructor now with inputId and inputText
 }

这里需要注意的是,我需要创建一个必须在使用后进行处理的对象。 (澄清:不是立即,但我必须调用 Dispose() 而不是等待垃圾收集)

但是,如果我在重载的构造函数中添加一些代码,我没有看到再次调用基本构造函数的方法。有没有办法从重载的构造函数中调用基本构造函数?

或者是否可以使用

public MyClass(MyOtherClass inputObject): this(inputObject.ID,
                                               inputObject.CreateHelper().Text) 
{}

这会自动处置从 CreateHelper() 生成的对象吗?

编辑:谢谢。两个问题:我不控制 MyOtherClass 并且我没有扩展方法(仅 .NET 3.0...)。不过,我确实控制了自己的类,而且由于我刚刚开始编写它,所以如果有好的方法,我可以毫无问题地重构构造函数。

最佳答案

用于解决此问题的最常见模式是让您的构造函数调用一个 Initialize() 方法,但在您刚刚给出的示例中,添加一个您调用的静态方法(如下面的代码)就可以解决问题。

public MyClass(MyOtherClass inputObject): this(inputObject.ID, GetHelperText(inputObject) {}

private static string GetHelperText(MyOtherClass o)
{
   using (var helper = o.CreateHelper())
      return helper.Text;
}

关于c# - 具有复杂逻辑的多个构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/109717/

相关文章:

c# - SQL Server批量插入/更新与插入或更新场景中的MERGE

javascript - 如何使用 ASP.NET Web API + AngularJs 基于 cookie 的身份验证来验证 cookie

c# - 不使用 IntPtr 的 SafeHandle

c# - 在 C# SOAP 中开始使用 Paypal 自适应支付

c# - 使用c#实现activeX控件在Windows窗体中查看PowerPoint幻灯片,不显示控件

c# - 在 C# 中使用谷歌翻译

c# - Entity Framework 迁移 - 启用 AutoMigrations 以及添加的迁移

c# - MySQL - Entity Framework 的问题

mysql - 如何从 .Net 时区转换为 MySQL 时区

c# - 引用 DLL 未在 Visual Studio 2010 中加载