关于C#中 get 和 set 的简单用法,大家看看

N_student 2009-11-28 02:06:07
代码入下:


class Wind
{
public string Color { get; set; }
public int Speed { get; set; }

static void Main(string[] args)
{
Wind northWind = new Wind{ Color = "Blue",Speed=10};
Wind southWind = new Wind{ Color = "Red", Speed = 5 };

Console.WriteLine("north wind's speed:{0}",northWind.Speed);
Console.ReadKey();
}


问题:
1.这里 public string Color { get; set; } get和set什么也没有做吗?不应该写 return一个值,value=一个值么?
2.Wind northWind = new Wind{ Color = "Blue",Speed=10}; 这句实现了给northWind赋了2属性值,是怎么实现的?

谢谢!
...全文
201 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
luxi0194 2009-11-28
  • 打赏
  • 举报
回复
呵呵,早就知道这个功能了。。。
mohugomohu 2009-11-28
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 whowhen21 的回复:]
好像不通过哦
[/Quote]
用2008就知道了
sunzihao128858 2009-11-28
  • 打赏
  • 举报
回复
错误代码,鉴定完毕!
trunjun 2009-11-28
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 trunjun 的回复:]
C# codepublicinterface IListSource
{// 摘要:// 获取表示集合是否是 System.Collections.IList 对象集合的值。//// 返回结果:// 如果集合是 System.Collections.IList 对象集合,则为 true;否则,为 false。bool ContainsListCollection {get;?-
[/Quote]
那这个里面的叫什么
trunjun 2009-11-28
  • 打赏
  • 举报
回复

public interface IListSource
{
// 摘要:
// 获取表示集合是否是 System.Collections.IList 对象集合的值。
//
// 返回结果:
// 如果集合是 System.Collections.IList 对象集合,则为 true;否则,为 false。
bool ContainsListCollection { get; }

// 摘要:
// 从不实现 System.Collections.IList 本身的对象返回可以绑定到数据源的 System.Collections.IList。
//
// 返回结果:
// 对象中可以绑定到数据源的 System.Collections.IList。
IList GetList();
}
N_student 2009-11-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 trunjun 的回复:]
public string Color { get; set; }
这是一个虚属性,就好像是接口里面的方法,int GetValue(),什么都没有。只有在用的时候实现它。
public int GetValue()
{
return 1;
}
同理:属性也是一样的。

[/Quote]

刚才查了一下,这个才是虚属性:


public abstract class Base
{
public abstract int Count
{
get;
}
public int Compute()
{
return Count;
}
}
public class Derived:Base
{
public override int Count
{
get {return 5;}
}
}
24K純帥 2009-11-28
  • 打赏
  • 举报
回复
这应该是.NET3.0才有的简化写法
pghgqg 2009-11-28
  • 打赏
  • 举报
回复
怪怪,偶也是一知半解
N_student 2009-11-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 mohugomohu 的回复:]
只是一个简化的语法。
就像Int32和int,没有什么区别
[/Quote]

我自己也倾向于是简化的写法
N_student 2009-11-28
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 trunjun 的回复:]
public string Color { get; set; }
这是一个虚属性,就好像是接口里面的方法,int GetValue(),什么都没有。只有在用的时候实现它。
public int GetValue()
{
return 1;
}
同理:属性也是一样的。

[/Quote]

虚属性?这个说法还真没听过!
闲着吃菜 2009-11-28
  • 打赏
  • 举报
回复
一般用到属性的都是private 为了保护变量用的。
你这里用的是Public 实际上就已经失去了使用属性的意义。
Color = "Blue",Speed=10;
因为你定义的属性是public 那么就可以直接赋值。在这里他其实就相当予你定义的两个个变量.
mohugomohu 2009-11-28
  • 打赏
  • 举报
回复
只是一个简化的语法。
就像Int32和int,没有什么区别
trunjun 2009-11-28
  • 打赏
  • 举报
回复
public string Color { get; set; }
这是一个虚属性,就好像是接口里面的方法,int GetValue(),什么都没有。只有在用的时候实现它。
public int GetValue()
{
return 1;
}
同理:属性也是一样的。

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧