【发布时间】:2014-02-12 00:28:09
【问题描述】:
这些是我的指示:
iii) 给 Pair 一个构造函数。
iv) 给 Pair 一个 set 属性,作为 key。
v) 还为 key 提供一个 get 属性。
在查看了我在这个论坛上可以找到的尽可能多的构造函数线程以获取信息后,我发现虽然给出的答案非常准确和准确,但我仍然没有完全理解。
我们被告知,如果定义了构造函数,则必须初始化所有属性,并且禁止对结构中的属性进行零碎初始化。
我的代码:
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
//
我的问题:
为什么我需要为 Pair 创建一个构造函数?
Pair two = new Pair();不就是这样做的吗?如果
Pair two = new Pair();是构造函数,那么它已经被定义了,对吧?如果它已被定义,我将如何避免出现下面列出的错误。我的讲师说“禁止对结构中的属性进行零碎初始化”是什么意思?我经常为编程世界中使用的术语而苦恼,所以请帮帮我:)
调试:
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)
编辑 更新代码:
现在它运行起来没有以前的错误。非常感谢大家解释得这么好!
但是,它提出了以下错误:pairapp.cs(14,14): error CS1520: Class, struct, or interface method must have a return type。查找后,我看不出它与以下示例中的示例有何不同:http://msdn.microsoft.com/en-us/library/aa288208(v=vs.71).aspx
我想要完成的(希望我没有弄糊涂自己)是创建一个构造函数,将值分配给结构的字段。 我做对了吗?
我还删除了下面的部分,因为在添加了下面更新版本中可以看到的内容之后感觉是多余的。
Pair two;
two = new Pair();
two.print();
我更新的代码:
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
//
【问题讨论】:
-
如果你把它交给同行评审,编译器会说同样的话。嗯?初始化键和颜色就是它所说的,或者添加一个这样做的构造函数。你会如何使用这个结构
标签: c# .net constructor attributes initialization