Sto provando a scrivere un metodo che trova tutti i tipi in un assembly con un attributo personalizzato specifico. Devo anche essere in grado di fornire un valore stringa da abbinare. L'avvertenza è che mi piacerebbe essere in grado di eseguire questo su qualsiasi classe e restituire qualsiasi valore.Richiama dinamicamente il valore dell'attributo di classe dal tipo
Per esempio: Vorrei eseguire una chiamata del genere
Type tTest = TypeFinder.GetTypesWithAttributeValue(Assembly.Load("MyAssembly"), typeof(DiagnosticTestAttribute), "TestName", "EmailTest");
Il mio metodo sembra così lontano come questo:
public static Type GetTypesWithAttributeValue(Assembly aAssembly, Type tAttribute, string sPropertyName, object oValue)
{
object oReturn = null;
foreach (Type type in aAssembly.GetTypes())
{
foreach (object oTemp in type.GetCustomAttributes(tAttribute, true))
{
//if the attribute we are looking for matches
//the value we are looking for, return the current type.
}
}
return typeof(string); //otherwise return a string type
}
mio attributo è simile al seguente:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class DiagnosticTestAttribute : Attribute
{
private string _sTestName = string.Empty;
public string TestName
{
get { return _sTestName; }
}
public DiagnosticTest(string sTestName)
{
_sTestName = sTestName;
}
}
Per chi ha familiarità con le espressioni, mi piacerebbe davvero essere in grado di effettuare una chiamata li ke:
TypeFinder.GetTypesWithAttributeValue<DiagnosticTestAttribute>(Assembly.Load("MyAssembly"), x=> x.TestName, "EmailTest");
Dove l'espressione utilizza il mio tipo generico per selezionare la proprietà che sto cercando.
Questo ha funzionato perfettamente. Ho dovuto cambiare l'assemblaggio come lo chiamavo da un altro ma funziona benissimo. Grazie mille. –
se potessi darti più cred vorrei ;-) – Seabizkit