簡體   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