Ich möchte statische Funktionen über DynamicObject ausführen, aber ich weiß nicht, wie saveOperation ausführen, ohne den Klassennamen typeof(Test1)
oder typeof(Test2)
anzugeben. Wie relise das besser?Dynamisches Objekt. Wie Funktion durch TryInvoke ausführen?
Zum Beispiel
class DynObj : DynamicObject
{
GetMemberBinder saveOperation;
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
saveOperation = binder;
result = this;
return true;
}
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
Type myType = typeof(Test1 or Test2 or ....);
result = myType.GetMethod(saveOperation.Name).Invoke(null, args);
return true;
}
}
class Program
{
static void Main(string[] args)
{
dynamic d1 = new DynObj();
d1.func1(3,6);
d1.func2(3,6);
}
}
class Test1
{
public static void func1(int a, int b){...}
}
class Test2
{
public static void func2(int a, int b){ ...}
}
Zweite Art und Weise definiert statische Funktion mit dem Attribut (von Carnifex angeboten)
class Test3
{
[DynFuncMemberAttribute]
public static void func3(int a, int b){...}
}
und bekommen Typ
public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
Type myType = null;
foreach (Type types in Assembly.GetExecutingAssembly().GetTypes())
{
foreach (MethodInfo mi in types.GetMethods())
{
foreach (CustomAttributeData cad in mi.CustomAttributes)
{
if (cad.AttributeType == typeof(DynFuncMemberAttribute))
{
myType = types;
break;
}
}
}
}
result = (myType != null)? myType.GetMethod(saveOperation.Name).Invoke(null, args): null;
return myType != null;
}
Vielen Dank für die Antwort Ich bearbeite meine Frage mit Ihrer Idee – askeet