通过属性的方法在C# [英] Pass Property to the Method in C#
问题描述
我需要通过一些类型的属性选择(每次一型),假设这是我喜欢的类型:
I need to pass selection of properties of some types(one type each time), assume this is my type:
public class Product {
[PrimaryKey]
public long Id { get; set; }
[DisplayName("Name")]
public string Title { get; set; }
[Foreignkey(Schema = "Products", Table = "MajorCategory", Column = "Id")]
[DisplayName("MCat")]
public string MajorCategory { get; set; }
[Foreignkey(Schema = "Products", Table = "Category", Column = "Id")]
[DisplayName("Cat")]
public string Category { get; set; }
public long CategoryId { get; set; }
[BoolAsRadio()]
public bool IsScanAllowed { get; set; }
}
所以,我需要一种方法来传递这个类型的属性到列表其他类型(目标类型),并且使用属性名和属性,而我不需要值,类似下面的伪代码:
So I need a way to pass the list of properties of this type to other Type(Target Type), and use property name, and attributes, and I don't need values, something like the following Pseudo-code:
List<Property> propertyList = new List<Property>();
propertyList.Add(Product.Id);
PropertyList.Add(Product.Title);
TargetType target = new TargetType();
target.Properties = propertyList;
public class TargetType {
public List<Property> Properties { get; set;}
GetAttributes() {
foreach(Property item in Properties){
Console.WriteLine(item.Name)
//Get Attributes
}
}
}
有没有办法通过,就像 Product.Id
和使用名称和该属性?我不知道,但也许的PropertyInfo
帮助,我想正好可以通过对象的名单,但在这种情况下,我不能使用属性和名称,你有什么建议,处理呢?或者这样的事情?如果我错了都让我怎么能实现呢?
Is there any way to pass just like Product.Id
and use name and attributes of that? I don't sure but maybe PropertyInfo
can help, I think just can pass List of Object but in that case I can't use attributes and names, what is your suggestion to handle this? or something like this? if I am wrong at all so how can I implement it?
推荐答案
您可以使用反射在.NET这里:
You can make use of reflection in .NET here:
List<PropertyInfo> propertyList = new List<PropertyInfo>();
Type productType = typeof (Product);
propertyList.Add(productType.GetProperty("Id"));
propertyList.Add(productType.GetProperty("Title"));
TargetType target = new TargetType();
target.Properties = propertyList;
public class TargetType {
public List<PropertyInfo> Properties { get; set;}
List<object> GetAttributes()
{
List<object> attributes = new List<object>();
foreach(PropertyInfo item in Properties)
{
Console.WriteLine(item.Name);
attributes.AddRange(item.GetCustomAttributes(true));
}
return attributes;
}
}
这篇关于通过属性的方法在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!