简体   繁体   English

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

[英]C# and readonly reference types (e.g., DataTable)

Let's say I have the following C# class: 假设我有以下C#类:

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

What's the meaning of readonly for reference types? 引用类型的readonly含义是什么? I just implemented this code and the user is atill able to modify the datatable. 我刚刚实现了这段代码,用户仍然可以修改数据表。

How can I prevent the user from writing or mutating my datatable (or any object in general)? 如何防止用户写入或更改我的数据表(或一般任何对象)? Ie, just read access. 即,只需读取访问权限即可。 Obviously using properties wouldn't help here. 显然,在这里使用属性无济于事。

Readonly means that you can not reassign the variable - eg later on you can not assign a new DataTable to dt. 只读意味着您不能重新分配变量-例如,以后您不能将新的DataTable分配给dt。

As for making the object itself read-only - that entirely depends on the object itself. 至于使对象本身为只读-完全取决于对象本身。 There is no global convention for making objects immutable. 没有使对象不可变的全局约定。

I didn't see anything specific to achieve this with .NET's DataTable but some options would be to 我没有看到使用.NET的DataTable实现此目的的任何具体方法,但有些选择是

  1. Ensure that the user doesn't have modify permissions in the database itself (most secure) 确保用户对数据库本身没有修改权限(最安全)
  2. Look for ReadOnly attributes on whatever grid/controls you are binding to it (also clear to the users then that this is read-only) 在要绑定到的任何网格/控件上查找ReadOnly属性(对用户也很清楚,这是只读的)

you can make a class like this: 您可以制作一个这样的课程:

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];
        }
    }



}

and use it like this example here: 并像下面的示例一样使用它:

 //in the Main method
 MyClass e = new MyClass();
 Console.WriteLine(e[0, 0]);//I added just one entry in the table

ofcourse if you wrote this statement 当然,如果你写这句话

e[0,0]=2;

it will produce an error similar to this: Property or indexer MyNameSpace.MyClass.this[int,int] cannot be assigned to --it is read only. 它将产生类似于以下错误:属性或索引器MyNameSpace.MyClass.this [int,int]无法分配给-它是只读的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM