专注于互联网--专注于架构

最新标签
网站地图
文章索引
Rss订阅

首页 »DotNet » 属性和字段的区别:C#中的字段与属性 »正文

属性和字段的区别:C#中的字段与属性

来源: 发布时间:星期三, 2008年9月24日 浏览:163次 评论:0
using System;
using System.Collections.Generic;
using System.Text;

namespace Example11_1 {
class Program {
static void Main(string[] args) {
Farmer farmer = new Farmer();
farmer.Name = "Liu";
farmer.Age = 226;

Console.WriteLine(farmer.Age);

Console.ReadLine();
}
}

class Farmer {
/// <summary>
/// Farmer类的无参数构造函数
/// </summary>
public Farmer() {
}

/// <summary>
/// Farmer类的构造函数
/// </summary>
/// <param name="m_Name">Farmer的姓名参数</param>
public Farmer(string m_Name) {
name = m_Name;
}

/// <summary>
/// 姓名字段
/// </summary>
string name = string.Empty;

/// <summary>
/// max字段
/// </summary>
const int max = 150;

/// <summary>
/// min字段
/// </summary>
const int min = 0;

/// <summary>
/// 年龄字段
/// </summary>
int age = 0;

/// <summary>
/// Max属性
/// </summary>
public int Max {
get {
return max;
}
}

/// <summary>
/// Min属性
/// </summary>
public int Min
{
get
{
return min;
}
}

/// <summary>
/// Name属性
/// </summary>
public string Name {
set {
name = value;
}
}

/// <summary>
/// 年龄属性
/// </summary>
public int Age {
get {
return age;
}
set {
if ((value > min) && (value < max))
{
age = value;
}
else
{
try
{
Exception ex = new Exception("设置的值超出预设范围!");
throw (ex);
}
catch
{

Console.WriteLine("设置的值超出预设范围!");

}
}
}
}
}

}

相关文章

读者评论

  • 共0条 分0页

发表评论

  • 昵称:
  • 内容: