Hi guys,
I have a class which contains ~ 200 properties. Out of those 200 properties
I need to access 10 (which I know beforehand already) via reflection in
another class.
Currently I am doing the following with my context object which represents
the class containing the 200 properties:
Type t = context.GetType();
foreach (PropertyInfo prop in t.GetProperties()
This brings me all 200 properties. Is there a way to use the BindingFlags
parameter and configure in the context class which properties so be used and
which not? Something like that:
[UseForReflectionAttribute]
public string frmOID
{
get { return "DoV1"; }
}
Thanks,
Martin
Marc Gravell - 19 May 2008 09:26 GMT
(resend; NNTP issues?)
Not via BindingFlags - but you can via TypeDescriptor.
Marc
using System;
using System.ComponentModel;
class Foo
{
static void Main()
{
Foo foo = new Foo();
foo.DateOfBirth = DateTime.Today;
foo.Name = "Fred";
foo.ShoeSize = 10;
Attribute[] attribs = {new InterestingAttribute()};
foreach(PropertyDescriptor prop in
TypeDescriptor.GetProperties(foo, attribs))
{
Console.WriteLine("{0}={1}", prop.Name,
prop.GetValue(foo));
}
}
public string Name { get; set; }
[Interesting]
public DateTime DateOfBirth { get; set; }
[Interesting]
public int ShoeSize { get; set; }
}
[AttributeUsage(AttributeTargets.Property,
AllowMultiple = false, Inherited = true)]
class InterestingAttribute : Attribute { }
Jeff Winn - 20 May 2008 14:53 GMT
If you wanted to use an attribute you'd have to enumerate through all of the
properties and test what attributes are on the property. If speed is an
issue, figure out which properties have the attribute applied to it for that
type and cache the results for easy retrieval later on. Once the class gets
checked over once, it won't have to worry about about finding them again. If
you need to have this handle across multiple objects, you may want to use an
in-memory collection similar to:
Dictionary<Type, Collection<PropertyInfo>> cache;
Collection<PropertyInfo> propertiesCollection = new
Collection<PropertyInfo>();
Type currentType = this.GetType();
foreach (PropertyInfo propInfo in currentType.GetProperties()) {
object[] attributes =
propInfo.GetCustomAttributes(typeof(UseForReflectionAttribute), true));
if (attributes == null || attributes.Length == 0) continue;
propertiesCollection.Add(propInfo)
}
this.cache.Add(currentType, propertiesCollection);
Now that the collection has been created for the current object, you'll want
to use it:
foreach (PropertyInfo propInfo in this.cache[this.GetType()]) {
// Do what you wanted to with your object here
}
Granted I don't know your situation, but something similar to what I've
demonstrated above should provide you with the flexibility you need and keep
it fast enough that you won't get a large degredation in speed while
enumerating through the properties on the object constantly.
> Hi guys,
>
[quoted text clipped - 19 lines]
>
> Martin