C#和只读引用类型(例如,DataTable)

时间:2014-12-19 19:47:39

标签: c# .net

假设我有以下C#类:

class MyClass ()
{
    public readonly DataTable dt = new DataTable();
    ...
}

引用类型readonly的含义是什么?我刚刚实现了这个代码,用户仍然可以修改数据表。

如何防止用户编写或更改我的数据表(或一般的任何对象)?即,只需读取访问权限。显然使用属性对此没有帮助。

3 个答案:

答案 0 :(得分:3)

Readonly意味着您无法重新分配变量 - 例如稍后您无法将新的DataTable分配给dt。

至于使对象本身是只读的 - 完全取决于对象本身。没有使对象成为不可变的全局约定。

我没有看到使用.NET的DataTable实现这一点的具体内容,但有些选项是

  1. 确保用户没有数据库本身的修改权限(最安全)
  2. 在您绑定到的任何网格/控件上查找ReadOnly属性(对用户也清楚,这是只读的)

答案 1 :(得分:2)

你可以创建一个这样的类:

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]无法分配给--it是只读的。

答案 2 :(得分:0)

readonly 表示 Datatable 将是运行时常量,而不是编译时常量