访问 C# 属性名称或特性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1407576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing C# property name or attributes
提问by FrenkR
I would like to automatically generate SQL statements from a class instance. The method should look like Update(object[] Properties, object PrimaryKeyProperty). The method is part of an instance (class, base method - generic for any child). Array of properties is an array of class properties, that will be used in updatestatement. Property names are equal to table field names.
我想从类实例自动生成 SQL 语句。该方法应该类似于 Update(object[] Properties, object PrimaryKeyProperty)。该方法是实例的一部分(类、基方法 - 对任何子项都是通用的)。属性数组是一个类属性数组,将在更新语句中使用。属性名称等于表字段名称。
The problem is that I can't get property names.
问题是我无法获得属性名称。
Is there any option to get a property name inside class instance? sample:
是否有任何选项可以在类实例中获取属性名称?样本:
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"
{
I am aware of PropertyInfo, but I don't know hot to get the ID of a property from GetProperties() array.
我知道 PropertyInfo,但我不知道从 GetProperties() 数组中获取属性 ID 的热度。
Any suggestion?
有什么建议吗?
回答by Vinay Sajip
You can do something like this:
你可以这样做:
Type t = someInstance.getType();
foreach (MemberInfo mi in t.GetMembers())
{
if (mi.MemberType == MemberTypes.Property)
{
Console.WriteLine(mi.Name);
}
}
to get all the property names for instance
's type.
获取instance
's 类型的所有属性名称。
回答by Rex M
Since you already have an explicit handle to the specific property you want, you know the name - can you just type it?
由于您已经拥有所需特定属性的显式句柄,因此您知道名称 - 可以直接输入吗?
回答by George Mauer
Just wrote an implementation of thisfor a presentation on lambdas for our usergroup last Tuesday.
上周二刚刚为我们的用户组编写了一个关于 lambdas 的演示文稿的实现。
You can do
MembersOf<Animal>.GetName(x => x.Status)
Or
var a = new Animal() a.MemberName(x => x.Status)
你可以做
MemberOf<Animal>.GetName(x => x.Status)
或者
var a = new Animal() a.MemberName(x => x.Status)
the code:
编码:
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;
}
}
- Link to the presentation and code samples.
- Also in SVN (more likely to be updated): http://gim-projects.googlecode.com/svn/presentations/CantDanceTheLambda
回答by Zach Johnson
You can get the name (I assume that's what you meant by ID) of a property using PropertyInfo.Name. Just loop through the PropertyInfo[] returned from typeof(className).GetProperties()
您可以使用 PropertyInfo.Name 获取属性的名称(我假设这就是您所说的 ID)。只需循环从 typeof(className).GetProperties() 返回的 PropertyInfo[]
foreach (PropertyInfo info in typeof(MyClass).GetProperties())
{
string name = info.Name;
// use name here
}
回答by FrenkR
Let's say (from the first sample, method update of a class MyClass
):
假设(从第一个示例中,类的方法更新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}
and {iMyKey}
are property values of a class instance.
{iMyStatusProperty}
和{iMyKey}
是类实例的属性值。
So, the problem is how to get property name (reflection) from a property without using names of properties as strings (to avoid field name typos).
因此,问题是如何从属性中获取属性名称(反射)而不使用属性名称作为字符串(以避免字段名称拼写错误)。
回答by Mehdi LAMRANI
I found a perfect solution in This Post
我在这篇文章中找到了一个完美的解决方案
public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
{
return (propertyExpression.Body as MemberExpression).Member.Name;
}
And then for the usage :
然后用于用法:
var propertyName = GetPropertyName(
() => myObject.AProperty); // returns "AProperty"
Works like a charm
奇迹般有效
回答by Contra
Not 100% sure if this will get you what you're looking for, this will fetch all properties with [Column] attribute inside your class: In the datacontext I have:
不是 100% 确定这是否会让你得到你想要的东西,这将在你的类中获取具有 [Column] 属性的所有属性:在数据上下文中我有:
public ReadOnlyCollection<MetaDataMember> ColumnNames<TEntity>( )
{
return this.Mapping.MappingSource.GetModel(typeof(DataContext)).GetMetaType(typeof(TEntity)).DataMembers;
}
Fetching the table column-names that are properties inside the class:
获取作为类内属性的表列名:
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);