Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 列出属性/检查属性是否为只读_.net_Wpf_Vb.net_Visual Studio - Fatal编程技术网

.net 列出属性/检查属性是否为只读

.net 列出属性/检查属性是否为只读,.net,wpf,vb.net,visual-studio,.net,Wpf,Vb.net,Visual Studio,在VB.net中,我面临几个问题:我有一系列对象,这些对象的属性显示在网格中,供用户编辑 我的第一个问题是:如何获得对象所有属性的列表?有可能吗?我正在使用的datagrid控件接受以属性名称作为参数的字符串值,但是手动插入它们将是一个真正的问题,因为其中有很多。那么:有没有一种方法可以获得包含对象每个属性名称的字符串列表 如果可能的话,下面是第二个问题: 当然,由于用户正在编辑属性,我对显示他们无法编辑的只读属性不感兴趣。因此,我的secodn问题是:有没有办法检查属性在运行时是否为只读 提前

在VB.net中,我面临几个问题:我有一系列对象,这些对象的属性显示在网格中,供用户编辑

我的第一个问题是:如何获得对象所有属性的列表?有可能吗?我正在使用的datagrid控件接受以属性名称作为参数的字符串值,但是手动插入它们将是一个真正的问题,因为其中有很多。那么:有没有一种方法可以获得包含对象每个属性名称的字符串列表

如果可能的话,下面是第二个问题: 当然,由于用户正在编辑属性,我对显示他们无法编辑的只读属性不感兴趣。因此,我的secodn问题是:有没有办法检查属性在运行时是否为只读


提前感谢您提供的任何帮助(即使这只是一个“无法完成的任务”)

您可以通过反射来完成。使用
foo.GetType()
获取特定对象的类型。然后使用
Type.GetProperties()
查找所有属性。对于每个属性,您可以使用
PropertyInfo.CanWrite
确定它是否可写

下面是一个简单的例子:

Option Strict On
Imports System
Imports System.Reflection

Public class Sample

    ReadOnly Property Foo As String
       Get
           Return "Foo!"
       End Get
    End Property

    Property Bar As String
       Get
           Return "Ar!"
       End Get
       Set
           ' Ignored in sample
       End Set
    End Property

End Class

Public Class Test

   Public Shared Sub Main()
       Dim s As Sample = New Sample()

       Dim t As Type = s.GetType()
       For Each prop As PropertyInfo in t.GetProperties
           Console.WriteLine(prop.Name)
           If Not prop.CanWrite
               Console.WriteLine("   (Read only)")
           End If
       Next prop
   End Sub

End Class

以下是如何循环使用
MyObject
中的属性。正如Jon Skeet所说,检查
CanWrite
,以帮助您回答问题的第二部分:

Dim MyProperties As System.Reflection.PropertyInfo() = MyObject.GetType().GetProperties()
For Each prop As System.Reflection.PropertyInfo In MyProperties
    If prop.CanWrite Then
        //do stuff
    End If
Next

谢谢Jon,快速清晰,正是我想要的。回答接受!