以下是可讀寫的:
private string mvarIniFilePath="";
public string IniFilePath
{
get{return (mvarIniFilePath);}
set{mvarIniFilePath = value;}
}/////////////////////////////以下是唯讀的:
private string mvarIniFilePath="";
public string IniFilePath
{
get{return (mvarIniFilePath);}
}
private string mvarIniFilePath="";
public string IniFilePath
{
get{return (mvarIniFilePath);}
set{mvarIniFilePath = value;}
}/////////////////////////////以下是唯讀的:
private string mvarIniFilePath="";
public string IniFilePath
{
get{return (mvarIniFilePath);}
}
{
public readonly int num;
public readonly int score=60;
//readonly字段可在声明时赋值,也可在构造函数中赋值,其他地方不可。 public const int age=22;
//public const int age;是个错误,const字段须在声明时赋值
public Student()
{
num=71;
score=100;
//age=22;这句话是个错误,const字段不可在除了声明以外的任何地方进行赋值
}
}class MainEntryPoint
{
static void Main()
{
Student Me=new Student();
Console.WriteLine(Me.num+" "+Me.score);
}
}//另外,只可在构造函数的参数中对readonly字段用ref或out关键字。
这里说的是只读引用,你给出的是属性的保护:只读或者只写等。只读引用在C++里面的作用是:即避免较复杂参数的复制(通过传引用或者传址),又能对参数进行保护防止函数改变,传达给调用者的信息就是,你调用我是安全的,不会对参数造成影响,这个很重要。
"在C#中,所有的引用类型,在参数传递时,都是按引用传递,所以不存在复制对象的开销"
那也未必啊,string類型是引用類型,Update時還不是要復制副本出來
二、保证不将任何不符合这两个条件的类的对象暴露出去,包括在读取器和属性中。或者在暴露时传出它的深拷贝(注意不是浅表拷贝)。
三、实例化这个类,并将其对象声明为readonly这个对象便是只读的。
class Test
{
public string s; public void TestString(string p_s)
{
if (Object.ReferenceEquals(p_s, s))
Console.WriteLine("string作为参数传递时,不产生另一个副本");
} }在Main()中,使用以下代码来测试
Test t = new Test();
t.s = "hello";
t.TestString(t.s);
readonly 关键字是可以在字段上使用的修饰符。当字段声明包括 readonly 修饰符时,该声明引入的字段赋值只能作为声明的一部分发生,或者发生在同一类的构造函数中。只能在下列上下文中进行只读字段的赋值: 当在声明中初始化变量时,例如:
public readonly int y = 5;
对于实例字段,在包含字段声明的类的实例构造函数中;或者,对于静态字段,在包含字段声明的类的静态构造函数中。只有在这些上下文中时,将 readonly 字段传递为 out 或 ref 参数才有效。 ××××××××××××××××
也就是说,建立一个这样的函数
public void TestFunc(readonly TestClass cla)
{
cla.mnValue ++;
}
将无法通过编译。期望用readonly来实现只读引用是行不通的。
可是.NET为什么不提供一个简明直观的机制呢?困惑中