【问题标题】:Accessing C# property name or attributes访问 C# 属性名称或属性
【发布时间】:2014-03-18 03:06:43
【问题描述】:

我想从类实例中自动生成 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。

有什么建议吗?

【问题讨论】:

    标签: c# properties


    【解决方案1】:

    Just wrote an implementation of this 上周二为我们的用户组介绍了 lambdas。

    • 你可以的

      MembersOf.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;
        }
    }
    

    【讨论】:

    • 嗨乔治,您的解决方案不适用于嵌套 Lambda,例如 MembersOf.GetName(x => x.Gender.Text) 应该给出“Gender.Text”,而不仅仅是“Text”。
    • @Stef,这是正确的。 x.Gender.Text 不是成员访问器。不过检查一下实现,让它检测整个语法树并重复递归应该相对容易
    • LukeH 在stackoverflow.com/questions/3049825/… 的回答正是我所需要的。
    • @GeorgeMauer 为什么不用 MembersOf.GetName&lt;T&gt;(Expression&lt;Func&lt;T,Object&gt;&gt; expr) 替换 MembersOf&lt;T&gt;.GetName&lt;R&gt;(Expression&lt;Func&lt;T,R&gt;&gt; expr),这样更简单,而且不需要特定的 R 类型(即使它是在编译时推断出来的) .
    • @YvesM。那会有什么优势呢?
    【解决方案2】:

    我在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"
    

    像魅力一样工作

    【讨论】:

      【解决方案3】:

      你可以这样做:

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

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

      【讨论】:

      • 他不想要所有的属性名,只想要特定的
      • 不确定是否值得反对。问题是,“是否有任何选项可以在类实例中获取属性名称?”我已经展示了一个循环,该循环通过打印类实例中的 all 属性名称,但他都可以将他想要更新的属性名称放入一个他传递给 Update 过程的数组中。我不明白问题出在哪里。
      【解决方案4】:

      您可以使用 PropertyInfo.Name 获取属性的名称(我假设这就是您所说的 ID)。只需循环从 typeof(className).GetProperties() 返回的 PropertyInfo[]

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

      【讨论】:

      • 我希望我能给你 +10 :)
      【解决方案5】:

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

      【讨论】:

      • 我认为他希望代码也适用于派生类,因此他需要使用反射。
      • 主要思想是不要重复名称。因此,当编写一个类(带有属性)时,我会自动生成表、CRUD 语句和 Intellisense
      【解决方案6】:

      不是 100% 确定这是否会为您提供所需的内容,这将获取您的类中具有 [Column] 属性的所有属性: 在我的数据上下文中:

       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);
      

      【讨论】:

        【解决方案7】:

        假设(从第一个示例中,类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} 是类实例的属性值。

        所以,问题是如何在不使用属性名称作为字符串的情况下从属性中获取属性名称(reflection)(以避免字段名称拼写错误)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-10-15
          • 1970-01-01
          • 1970-01-01
          • 2015-08-05
          相关资源
          最近更新 更多