关于在c#(.NET2.0)中运行时读取类属性的问题?

关于在c#(.NET2.0)中运行时读取类属性的问题?,c#,dynamic,runtime,properties,C#,Dynamic,Runtime,Properties,假设我有一个类有3个属性。直到运行时,我才知道要读取哪个属性。有没有一种不用switch/if-else语句的方法来实现这一点 如果一个DataTable被视为一个类,那么可以动态地处理这些列,这会起作用,但我无法将我的类更改为DataTable(说来话长) 对于DataTable,代码为: string columnName = "Age"; int age = dataRow[columnName]; 在课堂上这怎么可能 string propertyName = "Baka"; int

假设我有一个类有3个属性。直到运行时,我才知道要读取哪个属性。有没有一种不用switch/if-else语句的方法来实现这一点

如果一个DataTable被视为一个类,那么可以动态地处理这些列,这会起作用,但我无法将我的类更改为DataTable(说来话长)

对于DataTable,代码为:

string columnName = "Age";
int age = dataRow[columnName];
在课堂上这怎么可能

string propertyName = "Baka";
int age = item.getProperty(propertyName)  // ???

进行这种运行时评估的最简单方法是使用


根据您使用的.NET版本,您可以向类中添加方法或使用扩展方法。

执行此类运行时评估的最简单方法是使用


根据您使用的.NET版本,您可以向类中添加方法或使用扩展方法。

前面回答了类似的问题。这是一个代码示例,并链接到另一个问题。

您将对System.Reflection.PropertyInfo类的方法最感兴趣

C#代码示例

public bool SetProperty(object obj, string PropertyName, object val)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_info.SetValue(obj, val, null);
            return true;
        }
        catch (Exception ex) {
            return false;
        }
    }
    else {
        return false;
    }
}

public object GetProperty(object obj, string PropertyName)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_value = property_info.GetValue(obj, null);
            return property_value;
        }
        catch (Exception ex) {
            return null;
        }
    }
    else {
        return null;
    }
}
Public Function SetProperty(ByVal obj As Object, ByVal PropertyName As String, ByVal val As Object) As Boolean
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_info.SetValue(obj, val, Nothing)
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return False
    End If
End Function

Public Function GetProperty(ByVal obj As Object, ByVal PropertyName As String) As Object
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_value = property_info.GetValue(obj, Nothing)
            Return property_value
        Catch ex As Exception
            Return Nothing
        End Try
    Else
        Return Nothing
    End If
End Function
VB代码示例

public bool SetProperty(object obj, string PropertyName, object val)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_info.SetValue(obj, val, null);
            return true;
        }
        catch (Exception ex) {
            return false;
        }
    }
    else {
        return false;
    }
}

public object GetProperty(object obj, string PropertyName)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_value = property_info.GetValue(obj, null);
            return property_value;
        }
        catch (Exception ex) {
            return null;
        }
    }
    else {
        return null;
    }
}
Public Function SetProperty(ByVal obj As Object, ByVal PropertyName As String, ByVal val As Object) As Boolean
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_info.SetValue(obj, val, Nothing)
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return False
    End If
End Function

Public Function GetProperty(ByVal obj As Object, ByVal PropertyName As String) As Object
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_value = property_info.GetValue(obj, Nothing)
            Return property_value
        Catch ex As Exception
            Return Nothing
        End Try
    Else
        Return Nothing
    End If
End Function

早些时候回答了一个类似的问题。这是一个代码示例,并链接到另一个问题。

您将对System.Reflection.PropertyInfo类的方法最感兴趣

C#代码示例

public bool SetProperty(object obj, string PropertyName, object val)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_info.SetValue(obj, val, null);
            return true;
        }
        catch (Exception ex) {
            return false;
        }
    }
    else {
        return false;
    }
}

public object GetProperty(object obj, string PropertyName)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_value = property_info.GetValue(obj, null);
            return property_value;
        }
        catch (Exception ex) {
            return null;
        }
    }
    else {
        return null;
    }
}
Public Function SetProperty(ByVal obj As Object, ByVal PropertyName As String, ByVal val As Object) As Boolean
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_info.SetValue(obj, val, Nothing)
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return False
    End If
End Function

Public Function GetProperty(ByVal obj As Object, ByVal PropertyName As String) As Object
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_value = property_info.GetValue(obj, Nothing)
            Return property_value
        Catch ex As Exception
            Return Nothing
        End Try
    Else
        Return Nothing
    End If
End Function
VB代码示例

public bool SetProperty(object obj, string PropertyName, object val)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_info.SetValue(obj, val, null);
            return true;
        }
        catch (Exception ex) {
            return false;
        }
    }
    else {
        return false;
    }
}

public object GetProperty(object obj, string PropertyName)
{
    object property_value = null;
    System.Reflection.PropertyInfo[] properties_info = obj.GetType.GetProperties;
    System.Reflection.PropertyInfo property_info = default(System.Reflection.PropertyInfo);
    
    foreach (System.Reflection.PropertyInfo prop in properties_info) {
        if (prop.Name == PropertyName) property_info = prop; 
    }
    
    if (property_info != null) {
        try {
            property_value = property_info.GetValue(obj, null);
            return property_value;
        }
        catch (Exception ex) {
            return null;
        }
    }
    else {
        return null;
    }
}
Public Function SetProperty(ByVal obj As Object, ByVal PropertyName As String, ByVal val As Object) As Boolean
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_info.SetValue(obj, val, Nothing)
            Return True
        Catch ex As Exception
            Return False
        End Try
    Else
        Return False
    End If
End Function

Public Function GetProperty(ByVal obj As Object, ByVal PropertyName As String) As Object
    Dim property_value As Object
    Dim properties_info As System.Reflection.PropertyInfo() = obj.GetType.GetProperties
    Dim property_info As System.Reflection.PropertyInfo

    For Each prop As System.Reflection.PropertyInfo In properties_info
        If prop.Name = PropertyName Then property_info = prop
    Next

    If property_info IsNot Nothing Then
        Try
            property_value = property_info.GetValue(obj, Nothing)
            Return property_value
        Catch ex As Exception
            Return Nothing
        End Try
    Else
        Return Nothing
    End If
End Function
item.GetProperties()将返回一个PropertyInfo[],其中包含所有属性(我认为只有公共属性)

PropertyInfo对象有一个属性名,该属性名是该属性的名称,因此您可以使用您的搜索名在数组中迭代搜索PropertyInfo对象。

item.GetProperties()将返回一个包含所有属性的PropertyInfo[](我认为只有public)


PropertyInfo对象有一个属性名称,该名称是属性的名称,因此您可以使用搜索名称在数组中迭代搜索PropertyInfo对象。

如果您知道对象的类型,则可以使用反射获取所有属性,然后获取请求的属性

MyClass o;

PropertyInfo[] properties = o.GetType().GetProperties(
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

每个PropertyInfo都有一个名称,可以与字符串匹配。

如果您知道对象的类型,则可以使用反射获取所有属性,然后获取请求的属性

MyClass o;

PropertyInfo[] properties = o.GetType().GetProperties(
    BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

每个PropertyInfo都有一个名称,您可以将其与字符串匹配。

编辑:我刚刚阅读了您关于不使用开关的评论,但我还是会将其保留在这里,以防万一跳到我的第二个答案

也许是这样的:

public enum Property { Name, Age, DateOfBirth};

public T GetProperty<T>(Property property)
{
    switch (property)
    {
       case Property.Name:
          return this.Name;
       // etc.
    }
}
用法:

MyClass c = new MyClass(table.Rows[0]);
string name = c["Name"].ToString();
MyItem item = ...;
string propertyName = "Age";
int age = (int)item[propertyName];

编辑:我刚读到你关于不使用开关的评论,但无论如何我都会保留在这里,以防万一跳到我的第二个答案

也许是这样的:

public enum Property { Name, Age, DateOfBirth};

public T GetProperty<T>(Property property)
{
    switch (property)
    {
       case Property.Name:
          return this.Name;
       // etc.
    }
}
用法:

MyClass c = new MyClass(table.Rows[0]);
string name = c["Name"].ToString();
MyItem item = ...;
string propertyName = "Age";
int age = (int)item[propertyName];
示例使用:

用法:

MyClass c = new MyClass(table.Rows[0]);
string name = c["Name"].ToString();
MyItem item = ...;
string propertyName = "Age";
int age = (int)item[propertyName];
示例使用:

用法:

MyClass c = new MyClass(table.Rows[0]);
string name = c["Name"].ToString();
MyItem item = ...;
string propertyName = "Age";
int age = (int)item[propertyName];

它是一个小的、固定的属性集吗?可以使用
System.Reflection
,但这是非常重要的。特别是如果它看起来像一个简单的
开关
应该能够更干净地解决您的问题。大约有30个属性。。。我可以使用switch语句,但希望在此避免使用switch语句。您能详细说明一下您的用例吗?也许
字典
在这里更合适?您是否能够向类中添加一个DataTable字段,并通过在类中实现[]运算符来访问该字段?它是一个小的、固定的属性集,将被访问?可以使用
System.Reflection
,但这相当重要。特别是如果它看起来像一个简单的
开关
应该能够更干净地解决您的问题。大约有30个属性。。。我可以使用switch语句,但希望在此避免使用switch语句。您能详细说明一下您的用例吗?也许
字典
在这里更合适?您是否能够将DataTable字段添加到类中,并通过在类上实现[]运算符来访问该字段?当您在运行时之前不知道要获取哪个属性时,反射是我知道的唯一实用方法。其他方法可能包括某种类型的值字典,但反射将始终有效,并且可以在不使用额外内容的情况下应用于类。反射是我所知道的唯一实用的方法,当您在运行时之前不知道要使用哪个属性时,它可以获取属性。其他方法可能包括某种类型的值字典,但反射总是有效的,并且可以应用,而不会给类带来额外的麻烦