访问C#属性名称或属性 [英] Accessing C# property name or attributes
问题描述
我想自动生成一个类实例的SQL语句。该方法看起来应该像更新(对象[]属性,对象PrimaryKeyProperty)。该方法是一个实例(类的基本方法 - 通用所有子)的一部分。属性数组是类属性的数组,将在更新的语句中使用。属性名称等于表字段名称。
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 update statement. Property names are equal to table field names.
的问题是,我不能得到属性名称。
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"
{
我知道的PropertyInfo,但我不知道烫获取属性从的GetProperties的ID()数组。
I am aware of PropertyInfo, but I don't know hot to get the ID of a property from GetProperties() array.
任何建议?
推荐答案
的就写了这对lambda表达式为我们的最后一个星期二所在的用户组演示的实现。
Just wrote an implementation of this for a presentation on lambdas for our usergroup last Tuesday.
-
您可以做
You can do
MembersOf<动物> .GetName(X => x.Status)
MembersOf<Animal>.GetName(x => x.Status)
或
VAR一个=新的动物()
a.MemberName(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;
}
}
- 的链接到演示文稿和代码示例。
- 此外,在SVN(更可能被更新): http://gim-projects.googlecode.com/ SVN /简报/ CantDanceTheLambda
- Link to the presentation and code samples.
- Also in SVN (more likely to be updated): http://gim-projects.googlecode.com/svn/presentations/CantDanceTheLambda
这篇关于访问C#属性名称或属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!