在VS2008中C#实现了属性的自动读取/写入功能。那么这些自动实现的代码在VS2005中如何改写呢?
首先,更改.sln文件
![](https://img-blog.csdn.net/20140309121730000?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2Jpbl9ITEo4MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
把Format Version 10.00 -> Format Version 9.00
# Visual Studio 2008 -> # Visual Studio 2005
![](https://img-blog.csdn.net/20140309123419234?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2Jpbl9ITEo4MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
然后,改写geter/seter
// VS2008
- public string name { get; private set; }
// VS2005
- private string strName;
- public string name { get { return strName; } private set { this.strName = value; } }
最后,改写类的属性
// 类声明
- public class MyClass
- {
- public string firstName;
- public string lastName;
- }
// 赋值 - VS2008
- MyClass my = new MyClass() { firstName = "xiao", lastName = "bin" };
// 赋值 - VS2005
- MyClass my = new MyClass();
- my.firstName = "xiao";
- my.lastName = "bin";
执行结果:
![](https://img-blog.csdn.net/20140309124701421?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveGlhb2Jpbl9ITEo4MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
VS2008(Console Application)
Program.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
-
- namespace testProperties
- {
- public class MyClass
- {
- public string firstName;
- public string lastName;
- }
-
- class Program
- {
- public string name { get; private set; }
-
- static void Main(string[] args)
- {
- string strName = "My Name: ";
- MyClass my = new MyClass() { firstName = "xiao", lastName = "bin" };
-
- Program pm = new Program();
- pm.name = my.firstName + my.lastName;
- strName += pm.name;
-
- Console.WriteLine(strName);
- }
- }
- }
VS2005(Console Application)
Program.cs
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- namespace testProperty
- {
- public class MyClass
- {
- public string firstName;
- public string lastName;
- }
-
- class Program
- {
- private string strName;
- public string name { get { return strName; } private set { this.strName = value; } }
-
- static void Main(string[] args)
- {
- string strName = "My Name: ";
- MyClass my = new MyClass();
- my.firstName = "xiao";
- my.lastName = "bin";
-
- Program pm = new Program();
- pm.name = my.firstName + my.lastName;
- strName += pm.name;
-
- Console.WriteLine(strName);
- }
- }
- }
参考文章:
1. Auto-Implemented Properties