C#中基于RunBefore特性对方法排序的最优实现方案
按RunBefore特性规则排序方法
需要实现一种根据方法特性值对方法进行排序的逻辑,使得标记了RunBefore特性的方法,始终排在该特性参数指定的方法之前。
代码示例
class Program { static void Main() { var classType = typeof(MethodsTest); var methods = classType.GetMethods() .Where( m => m.Name.StartsWith("Test") ) .OrderBy(/* ??? */) .ToArray(); } } class MethodsTest { public void TestUnrelatedMethod() { } public void TestMethod() { } [RunBefore(nameof(TestMethod))] public void TestBeforeMethod() { } [RunBefore(nameof(TestBeforeMethod))] public void TestBeforeOther() { } } public class RunBeforeAttribute : Attribute { public string methodName; public string callerName; public RunBeforeAttribute(string method, [CallerMemberName] string callerMember = null) { methodName = method; callerName = callerMember; } }
预期排序结果
预期排序后的MethodInfo数组顺序为:
TestBeforeOther TestBeforeMethod TestMethod TestUnrelatedMethod
当前尝试的写法
我目前尝试了如下写法,但不确定是否正确:
.OrderBy( m => m.GetCustomAttributes(typeof(RunBeforeAttribute), false).First(), /* */ ) )
内容的提问来源于stack exchange,提问作者Markus
相关产品推荐
相关产品推荐

