用于将值从属性传递到方法的模式

时间:2016-12-15 21:49:55

标签: c# .net reflection

我试图找出一种传递方法属性的无缝方法。这是一个可能的实现:

    [Custom(Greeting = "Hello")]
    public string Test(string name)
    {
        var attributes = MethodInfo.GetCurrentMethod().GetCustomAttributes();
        return SayGreeting(attributes, name);
    }

    private string SayGreeting(IEnumerable<Attribute> attributes, string name)
    {
        var customAttr = attributes.SingleOrDefault(a => a is CustomAttribute) as CustomAttribute;
        return customAttr?.Greeting + " " + name;
    }

然而,问题是:

  1. 使用异步方法时会崩溃。
  2. 它不支持从接口获取属性。
  3. 它看起来很难看,特别是当一个类有很多方法时。在处理问题1和问题2时,它看起来也会更加难看。
  4. 我认为我可以通过使用callermembername修复问题1,然后使用反射获取方法。然后,我可以通过使用更多反射来修复问题2.

    另一种(可能更优雅)修复它的方法是使用Castle DynamicProxy或.NET的RealProxy。在我走这条路之前,我想知道是否有人有其他建议吗?

    谢谢,

0 个答案:

没有答案