CSharp · Console
using System;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main()
{
TestObject test = new TestObject();
Console.WriteLine(test.testfld1.GetFieldAttr().Text);
Console.WriteLine(test.testfld2.GetFieldAttr().Text);
Console.WriteLine(test.testfld3.GetFieldAttr().Text);
}
}
public static class Extensions
{
public static FieldAttr GetFieldAttr(this object source)
{
var test = typeof (TestObject);
var type = test.GetFields()
.FirstOrDefault(x => x.FieldType == source.GetType());
if (type != null)
{
var attribute = type.GetCustomAttribute<FieldAttr>();
return attribute;
}
return null;
}
}
public class TestObject
{
// Declare fields
[FieldAttr("prop_testfld1")]
public FLDtype1 testfld1 = new FLDtype1();
[FieldAttr("prop_testfld2")]
public FLDtype2 testfld2 = new FLDtype2();
[FieldAttr("prop_testfld3")]
public FLDtype1 testfld3 = new FLDtype1();
}
public class FLDtype1
{
public string Value { get; set; }
}
public class FLDtype2
{
public Guid Value { get; set; }
}
public sealed class FieldAttr : System.Attribute
{
private string _txt;
public FieldAttr(string txt)
{
this._txt = txt;
}
public string Text { get { return this._txt; } }
}