使用这个()在C#构造函数 [英] Using this() in C# Constructors

查看:108
本文介绍了使用这个()在C#构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图找出是否有这些构造函数之间的差异。假设有一个Foo()构造不带任何参数,都是这些构造将有同样的结果?

实施例1

 公共美孚()
    : 这个()
{
     等等;
     等等;
     等等;
}

实施例2

 公共美孚()
{
     这个();
     等等;
     等等;
     等等;
}

实施例3

 公共美孚()
{
     该=新的Foo();
     等等;
     等等;
     等等;
}


解决方案

  • 例1是有效的(假设有一个参数的构造函数),并调用参数的构造函数初始化过程。参见构造我的文章链接了解更多详情。编辑:请注意,由于OP的编辑,这是无限递归

  • 例2是永远不会有效

  • 例3只有当美孚是一个结构有效,并且没有做任何有用的事情。

我会避开在结构中分配给这个的。你可以从其他的答案看到,非常的可能的中它是相当鲜为人知的(我只知道因为一些奇怪的情况:它在规范止跌回升)。在这里你已经得到它,它不会做任何好处 - 而在其他地方,它很可能是变异的结构,这是的的一个好主意。结构应该总是一成不变的:)

编辑:只是为了让人们去MEEP!一点点 - 分配给这个是不太一样的只是链接到另一个构造函数,你可以做到这一点的方法太:

 使用系统;公共结构美孚
{
    //只读,因此必须是不可变的,对不对?
    公共只读字符串x;    公共美孚(字符串x)
    {
        this.x = X;
    }    公共无效EvilEvilEvil()
    {
        该=新的Foo();
    }
}公共类测试
{
    静态无效的主要()
    {
        富富=新的Foo(测试);
        Console.WriteLine(foo.x); //打印测试
        foo.EvilEvilEvil();
        Console.WriteLine(foo.x); //输出什么
    }
}

I have been trying to figure out if there are any differences between these constructors. Assuming there is a Foo() constructor that takes no arguments, are all these constructors going to have the same result?

Example 1

public Foo()
    : this()
{
     blah;
     blah;
     blah;
}

Example 2

public Foo()
{
     this();
     blah;
     blah;
     blah;
}

Example 3

public Foo()
{
     this = new Foo();
     blah;
     blah;
     blah;
}

解决方案

  • Example 1 is valid (assuming there is a parameterless constructor), and calls the parameterless constructor as part of initialization. See my article on constructor chaining for more details. EDIT: Note that since the OP's edit, it's infinitely recursive.
  • Example 2 is never valid
  • Example 3 is only valid when Foo is a struct, and doesn't do anything useful.

I would steer clear of assigning to this in structs. As you can see from the other answers, the very possibility of it is fairly rarely known (I only know because of some weird situation where it turned up in the spec). Where you've got it, it doesn't do any good - and in other places it's likely to be mutating the struct, which is not a good idea. Structs should always be immutable :)

EDIT: Just to make people go "meep!" a little - assigning to this isn't quite the same as just chaining to another constructor, as you can do it in methods too:

using System;

public struct Foo
{
    // Readonly, so must be immutable, right?
    public readonly string x;

    public Foo(string x)
    {
        this.x = x;
    }

    public void EvilEvilEvil()
    {
        this = new Foo();
    }
}

public class Test
{
    static void Main()
    {
        Foo foo = new Foo("Test");
        Console.WriteLine(foo.x); // Prints "Test"
        foo.EvilEvilEvil();
        Console.WriteLine(foo.x); // Prints nothing
    }
}

这篇关于使用这个()在C#构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆