繁体   English   中英

访问C#属性名称或属性

[英]Accessing C# property name or attributes

我想从类实例中自动生成SQL语句。 该方法应该看起来像Update(object [] Properties,object PrimaryKeyProperty)。 该方法是实例的一部分(类,基本方法 - 任何子代的通用)。 属性数组是类属性的数组,将在update语句中使用。 属性名称等于表字段名称。

问题是我无法获得属性名称。

有没有选项在类实例中获取属性名称? 样品:

public class MyClass {
public int iMyProperty { get; set; }
public string cMyProperty2 { get; set; }
{

main() {
 MyClass _main = new MyClass();

_main.iMyProperty.*PropertyName* // should return string "iMyProperty"

{

我知道PropertyInfo,但我不知道从GetProperties()数组中获取属性的ID。

有什么建议吗?

上周二为我们的用户组编写了一个关于lambda的演示文稿。

  • 你可以做

    MembersOf <Animal> .GetName(x => x.Status)

  • 要么

    var a = new Animal()a.MemberName(x => x.Status)

代码:

public static class MembersOf<T> {
    public static string GetName<R>(Expression<Func<T,R>> expr) {
        var node = expr.Body as MemberExpression;
        if (object.ReferenceEquals(null, node)) 
            throw new InvalidOperationException("Expression must be of member access");
        return node.Member.Name;
    }
}

我在This Post找到了一个完美的解决方案

public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
   return (propertyExpression.Body as MemberExpression).Member.Name;
}

然后用于:

var propertyName = GetPropertyName(
() => myObject.AProperty); // returns "AProperty"

奇迹般有效

你可以这样做:

Type t = someInstance.getType();

foreach (MemberInfo mi in t.GetMembers())
{
    if (mi.MemberType == MemberTypes.Property)
    {
        Console.WriteLine(mi.Name);
    }
}

获取instance类型的所有属性名称。

您可以使用PropertyInfo.Name获取属性的名称(我假设这是您对ID的含义)。 只需遍历从typeof(className)返回的PropertyInfo [] .GetProperties()

foreach (PropertyInfo info in typeof(MyClass).GetProperties())
{
    string name = info.Name;
    // use name here
}

由于您已经拥有所需特定属性的显式句柄,因此您知道名称 - 您可以输入它吗?

让我们说(从第一个示例,类MyClass方法更新):

public class MyClass {

public int iMyStatusProperty { get; set; }
public int iMyKey { get; set; }

public int UpdateStatusProperty(int iValue){
this.iMyStatusProperty = iValue;
return _Update( new[iMyStatusProperty ], iMyKey); // this should generate SQL: "UPDATE MyClass set iMyStatusProperty = {iMyStatusProperty} where iMyKey = {iMyKey}"
}

{iMyStatusProperty}{iMyKey}是类实例的属性值。

因此,问题是如何从属性获取属性名称( 反射 )而不使用属性名称作为字符串(以避免字段名称拼写错误)。

不是100%确定这是否能满足您的需求,这将获取您类中[Column]属性的所有属性:在datacontext中我有:

 public ReadOnlyCollection<MetaDataMember> ColumnNames<TEntity>( )
    {
        return this.Mapping.MappingSource.GetModel(typeof(DataContext)).GetMetaType(typeof(TEntity)).DataMembers;
    }

获取作为类内属性的表列名:

       MyDataContext db = GetDataContext(); 
       var allColumnPropertyNames =   db.ColumnNames<Animal>().Where(n => n.Member.GetCustomAttributes(typeof(System.Data.Linq.Mapping.ColumnAttribute), false).FirstOrDefault() != null).Select(n => n.Name);

暂无
暂无

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

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