You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 12:39:51