为什么using语句内的变量不能修改?如果我有以下代码:using(S s new S()){s.x 2s.y 3}编译器会提示
为什么using语句内的变量不能修改? 如果我有以下代码:
using(S s = new S()) { s.x = 2; s.y = 3; }
编译器会提示我Cannot modify members of 's' because it is a 'using variable' 这是为什么呢? 如果一个变量声明了就不能再修改了,那应该有readonly/const之类的修饰啊,为什么using了就不能修改了? [解决办法] 如果S仅是一个对象,你这样使用是没有什么意义的,using一般用天连接数据,然后对数据库中的对象操作
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { using (S s = new S()) { Console.WriteLine(s); s.x = 2; s.y = 3; Console.WriteLine(s); } Console.ReadKey(); } }
public class S : IDisposable { public int x { get; set; } public int y { get; set; }