简体   繁体   English

构造函数混淆 - '从未分配给,并且将始终具有其默认值'

[英]Constructor Confusion - 'never assigned to, and will always have its default value'

These are my instructions: 这些是我的指示:

iii) Give Pair a constructor. iii)给Pair一个构造函数。
iv) Give Pair a set property, for key. iv)为密钥提供一对set属性。
v) Also provide a get property for key. v)还提供key的get属性。

After having checked out as many constructor threads I could find on this forum for information, I found that although the answers given were very accurate and precise, there's still something I don't fully understand. 在查看了我可以在此论坛上找到的尽可能多的构造函数线程之后,我发现虽然给出的答案非常准确和准确,但仍然有一些我不完全理解的东西。

We were told that if a constructor is defined at all then all the attributes must be initialised as well as that piece-meal intialisation of attributes in a struct is forbidden. 我们被告知,如果完全定义了构造函数,那么必须初始化所有属性,以及禁止在结构中使用元素初始化属性。

My code: 我的代码:

 using System ;
   using System.Drawing ; 
   // above namespace 
   // has the class Color 

   public class PairApp
   {
      public static void Main()
      {
            Pair two = new Pair();
            two.print(); 
      }

      struct Pair
      {

                int key;
                Color colour;


                public void print()
                {
                    Console.WriteLine("key : " + key );
                    Console.WriteLine("colour : " + colour);
                }
      }
   }
   //
   // Some values from the 
   // class Color
   //    Color.Red
   //    Color.Cyan
   //    Color.DarkGray
   //

My questions: 我的问题:

  1. Why would I need to create a constructor for Pair? 为什么我需要为Pair创建构造函数? Isn't that what Pair two = new Pair(); 这不是什么Pair two = new Pair(); does? 呢?

  2. If Pair two = new Pair(); 如果Pair two = new Pair(); is the constructor, then it has been defined, right? 是构造函数,然后它被定义,对吧? If it has been defined, how would I go about not getting the errors listed below. 如果已定义,我将如何得不到下面列出的错误。

  3. What does my lecturer mean when he states that 'piece-meal initialisation of attributes in a struct is forbidden'? 当他说“结构中属性的零碎初始化被禁止”时,我的讲师意味着什么? I often struggle with the terminology used within the programming world so help me out :) 我经常讨论编程世界中使用的术语,所以帮助我:)

Debug: 调试:

airapp.cs(17,16): warning CS0649: Field `PairApp.Pair.key' is never assigned to, and will always have its default value `0'
pairapp.cs(18,18): warning CS0649: Field `PairApp.Pair.colour' is never assigned to, and will always have its default value
Compilation succeeded - 2 warning(s)

EDIT UPDATED CODE: 编辑更新代码:

Now it runs with none of the errors it had before. 现在它运行时没有任何错误。 A massive thanks to everyone for explaining it so well! 非常感谢大家对它的解释!

However, it puts forth the following error: pairapp.cs(14,14): error CS1520: Class, struct, or interface method must have a return type . 但是,它提出了以下错误: pairapp.cs(14,14): error CS1520: Class, struct, or interface method must have a return type After looking it up I don't see how it's any different to the example shown at: http://msdn.microsoft.com/en-us/library/aa288208(v=vs.71).aspx 在查找之后,我看不出它与以下示例有什么不同: http//msdn.microsoft.com/en-us/library/aa288208(v = vs.71).aspx

What I'm trying to accomplish (hope I've not managed to confuse myself) is to create a constructor that assigns the values to the fields of the struct. 我想要完成的事情(希望我没有设法让自己迷惑)是创建一个构造函数,将值分配给结构的字段。 Have I done this correctly? 我做得对吗?

I have also removed the below section as it felt superfluous after having added what can be seen in the updated version further below. 我还删除了以下部分,因为在添加了下面更新版本中可以看到的内容之后感觉多余。

Pair two;

        two = new Pair();
        two.print();

My updated code: 我的更新代码:

using System ;
   using System.Drawing ; 
   // above namespace 
   // has the class Color 

   public class PairApp
   {
      public static void Main()
      {

            Lion p1 = new Lion(5, Color.Red);
            p1.print(); 
      }
      public Lion(int key, Color colour)
      {
            this.key = key;
            this.colour = colour;
      } 
      struct Pair
      {

                int key;
                Color colour;


                public void print()
                {
                    Console.WriteLine("key : " + key );
                    Console.WriteLine("colour : " + colour);
                }
      }
   }
   //
   // Some values from the 
   // class Color
   //    Color.Red
   //    Color.Cyan
   //    Color.DarkGray
   //
  1. You don't need to create a constructor for Pair because it will work just fine with its default constructor (the example that you've listed). 你并不需要创建一个对构造,因为它的作用与它的默认构造函数(即您所列出的例子)的罚款。 But if your struct has fields that should be initialized with certain values, it's a good idea to create a constructor that takes those values and constructs your struct for you right away. 但是,如果您的struct具有应该使用某些值初始化的字段,那么创建一个构造函数是个好主意,该构造函数会立即获取这些值并为您构造结构。 The default constructor will not initialize your fields for you with anything other than their default values (as shown in your error output). 默认构造函数不会使用除默认值之外的任何内容为您初始化字段(如错误输出中所示)。

    Which brings us to your next question... 这将我们带到您的下一个问题......

  2. A type can in fact have one or more constructors. 事实上,一个类型可以有一个或多个构造函数。 The one you've listed is the default constructor, which is created automatically if you don't write any of your own and takes no parameters and does nothing aside from allowing an instance of your struct to be created in memory. 您列出的是默认构造函数,如果您不编写任何自己的参数并且不使用任何参数,则会自动创建,除了允许在内存中创建结构实例之外什么都不做。

    In your case, you'll want to make a constructor that takes two parameters, key and colour , and assigns them to the fields in your struct. 在您的情况下,您将需要创建一个带有两个参数( keycolour的构造函数,并将它们分配给结构中的字段。 The signature should look like public Pair(int key, Color colour) , and you'll need to assign the fields this.key and this.colour to those parameters in your constructor. 签名应该看起来像public Pair(int key, Color colour) ,并且您需要将this.keythis.colour字段分配给构造函数中的那些参数。

  3. Piecemeal initialization in this case probably just refers to initializing only some of the fields and not all of them (that word doesn't have any programming-specific meaning that I know of). 在这种情况下,零碎的初始化可能仅仅是指初始化一些字段而不是所有字段(该字不具有我所知道的任何特定于编程的含义)。

    The warnings that you see are precisely the consequence of leaving certain fields uninitialized or unassigned in code. 您看到的警告正是在代码中保留未初始化或未分配的某些字段的结果。 As another example, if you made a constructor that only assigned a value to key , but never to colour , what would the output be? 另一个例子,如果你创建的构造函数只为key赋值,但从不colour ,那么输出会是什么?


There are two problems with your constructor: 构造函数有两个问题:

  1. It needs to be the same name as the type it is constructing. 它需要与它正在构造的类型相同。 So in this case, it's Pair . 所以在这种情况下,它是Pair (Turns out there was a typo in my answer which might have misled you, I've fixed that now.) (事实证明我的答案中有一个错字,可能误导了你,我现在已经修好了。)

  2. It needs to appear inside the struct definition, not alongside it. 它需要出现结构定义中,而不是它旁边。 (In other words, alongside the fields and methods within the struct itself.) (换句话说,与结构本身的字段和方法一起。)

Pair two = new Pair();

is not a constructor, it's assigning instance of Pair to local variable. 它不是构造函数,它将Pair的实例分配给局部变量。 Instance is created by using constructor, but it's not defined here. 实例是使用构造函数创建的,但这里没有定义。

Constructor is a thing, defined inside your class. 构造函数是在类中定义的东西。 It looks like a method without return value and can have overrides with parameters (to ease your life). 它看起来像一个没有返回值的方法,可以覆盖参数(以减轻你的生活)。

struct Pair
{
    public Pair() {} // constructor
}

This sounds wrong or you rephrase it to be wrong: 这听起来错了,或者你改写它是错误的:

if a constructor is defined at all then all the attributes must be initialised as well as that piece-meal intialisation of attributes in a struct is forbidden 如果完全定义了构造函数,则必须初始化所有属性,以及禁止对结构中的属性进行分段初始化

Your issue is access modifiers . 您的问题是访问修饰符 By default your fields are private (if I remember right in C++ struct has by default public fields, this is probably the reason of confusion). 默认情况下,您的字段是private (如果我记得在C++ struct中默认使用公共字段,这可能是混淆的原因)。 Because you don't define any constructor - default is used (which is only allocates memory for all fields, but is not assigning any value to them). 因为您没有定义任何构造函数 - 使用默认值(它仅为所有字段分配内存,但为它们分配任何值)。

Private fields and no field initialization in constructor (actually, no constructor defined) in the struct - means you are not assigning anything to it at all (you are only using values in print method). 结构中的私有字段和构造函数中没有字段初始化(实际上, 没有构造函数定义) - 意味着您根本没有为其分配任何内容(您只在print方法中使用值)。 This makes compiler sure, what you are mistaken somewhere. 这使编译器确定,你在某处错了。 Adding any sort of settings will make compiler shut =D 添加任何类型的设置都会使编译器关闭 = D.

struct Pair
{
    int key;
    Color colour;

    public void print()
    {
        Console.WriteLine("key : " + key );
        Console.WriteLine("colour : " + colour);
    }

    // no more warning, but.. are you sure? 
    public void LOL()
    {
        key = 0;
        Color = Color.Red;
    }
}   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 构造函数DI - Field永远不会分配给,并且始终具有其默认值 - Constructor DI - Field is never assigned to, and will always have its default value 永远不会分配给,并且将始终具有其默认值 0 - is never assigned to, and will always have its default value 0 从未分配给它,并且将始终具有其默认值 - is never assigned to, and will always have its default value 字段从未分配给它,并且将始终具有其默认值 - Field is never assigned to, and will always have its default value 字段“ FIELD”从未分配,并且将始终具有其默认值 - field 'FIELD' is never assigned to, and will always have its default value 警告:永远不会将字段分配给,并且始终将其默认值设置为null - Warning: Field is never assigned to, and will always have its default value null 字段'xxx'永远不会分配给,并且将始终具有其默认值null - Field 'xxx' is never assigned to, and will always have its default value null 永远不会将字段xxx分配给,并始终将其默认值设置为null - Field xxx is never assigned to, and will always have its default value null 字段…永远不会分配给它,并且其默认值始终为null - Field … is never assigned to, and will always have its default value null 该字段永远不会分配给它,并且其默认值始终为null - The Field Is Never Assigned To And Will Always Have Its Default Value null
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM