![](/img/trans.png)
[英]c# - should I use “ref” to pass a collection (e.g. List) by reference to a method?
[英]C# and readonly reference types (e.g., DataTable)
假設我有以下C#類:
class MyClass ()
{
public readonly DataTable dt = new DataTable();
...
}
引用類型的readonly
含義是什么? 我剛剛實現了這段代碼,用戶仍然可以修改數據表。
如何防止用戶寫入或更改我的數據表(或一般任何對象)? 即,只需讀取訪問權限即可。 顯然,在這里使用屬性無濟於事。
只讀意味着您不能重新分配變量-例如,以后您不能將新的DataTable分配給dt。
至於使對象本身為只讀-完全取決於對象本身。 沒有使對象不可變的全局約定。
我沒有看到使用.NET的DataTable實現此目的的任何具體方法,但有些選擇是
您可以制作一個這樣的課程:
class MyClass
{
private DataTable dt = new DataTable();
public MyClass()
{
//initialize your table
}
//this is an indexer property which make you able to index any object of this class
public object this[int row,int column]
{
get
{
return dt.Rows[row][column];
}
}
/*this won't work (you won't need it anyway)
* public object this[int row][int col]*/
//in case you need to access by the column name
public object this[int row,string columnName]
{
get
{
return dt.Rows[row][columnName];
}
}
}
並像下面的示例一樣使用它:
//in the Main method
MyClass e = new MyClass();
Console.WriteLine(e[0, 0]);//I added just one entry in the table
當然,如果你寫這句話
e[0,0]=2;
它將產生類似於以下錯誤:屬性或索引器MyNameSpace.MyClass.this [int,int]無法分配給-它是只讀的。
readonly表示Datatable將是運行時常量,而不是編譯時常量
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.