假设我有一个这样的类:如何使用C#属性基于字符串在类中选择方法?
public class MyMethods
{
[SpecialMethod("test")]
public string GetTestString(int i)
{
return string.Format("Hello world {0} times!",i);
}
[SpecialMethod("lorem")]
public string GetSomeLoremIpsumText(int i)
{
// ignores the 'i' variable
return "Lorem ipsum dolor sit amet";
}
// ... more methods with the same signature here ...
public string DefaultMethod(int i)
{
return "The default method happened! The attribute wasn't found.";
}
public string ThisMethodShouldNotShowUpViaAttributes(int i)
{
return "You should not be here.";
}
}
我也有定义的属性只是这样的:
[AttributeUsage(AttributeTargets.Method)]
public class SpecialMethodAttribute : System.Attribute
{
private string _accessor;
public string Accessor
{
get
{
return _accessor;
}
}
public SpecialMethodAttribute(string accessor)
{
_accessor = accessor;
}
}
我希望能够做的可能是这样的内容:
public class MethodAccessViaAttribute
{
private MyMethods _m;
public MethodAccessViaAttribute()
{
_m = new MyMethods();
}
public string CallMethodByAccessor(string accessor, int i)
{
// this is pseudo-code, expressing what I want to be able to do.
Func<int, string> methodToCall = FindAMethodByAttribute(_m, accessor);
if (methodToCall == null)
return _m.DefaultMethod(i);
else
return methodToCall(i);
}
public void Test()
{
// should print "Hello world 3 times!"
Console.WriteLine(CallMethodByAccessor("test",3));
// should print "Lorem ipsum dolor sit amet"
Console.WriteLine(CallMethodByAccessor("lorem",int.MaxValue));
// should print "The default method happened! The attribute wasn't found."
Console.WriteLine(CallMethodByAccessor("I-do-not-exist",0));
}
}
请注意,所有使用SpecialMethod
属性的方法都遵循相同的方法签名。理想情况下,搜索功能将排除不匹配签名的方法,因为可以使用try/catch
来测试方法是否与Func
签名匹配。
我可以在正确的方向得到一个关于如何完成这一点的观点吗?
这听起来像你应该重新考虑这种方法。基于“访问者”这个单词,你可能会在一个单一的方法内插入一个开关盒。除了属性之外,您可以通过几种不同的方式来完成此操作。我很好奇,这种代码的用例是什么? – JuanR
我在写一个库,我希望能够导入到另一个项目中。因此对这些案例进行硬编码是不可接受的。我希望能够添加一个新的可能的方法,只需添加一个具有正确签名和相应属性的新方法即可。由于.NET自己的单元测试基本上使用了这样的方法,因此标记应该用[TestMethod]调用的方法,我认为有一种方法可以实现这一点。 – fdmillion
我建议你看看接口(认为插件模式)。我会做的是创建一个接口来表示实现该方法的对象。然后,我可以加载程序集并查找实现此接口的类,实例化它们并调用方法。 – JuanR