gpt4 book ai didi

c# - 如何在运行时获取方法的名称?

转载 作者:行者123 更新时间:2023-11-30 21:55:27 25 4
gpt4 key购买 nike

我使用的事件系统采用字符串作为回调方法名称。我想避免硬编码字符串。有什么方法可以在运行时获取给定类的方法名称?

类似于:

typeof(MyClass).Name;

但对于方法来说就完美了。

编辑:

我一直在谷歌搜索这个问题,所有结果似乎都是人们在寻找当前执行方法的名称。这不是我要找的 - 相反,我想获取同一类中其他方法的名称。

最佳答案

听起来您在谈论 C# 6.0 中添加的 nameof 运算符。

MSDN Documentation

摘录:

Used to obtain the simple (unqualified) string name of a variable, type, or member. When reporting errors in code, hooking up model-view-controller (MVC) links, firing property changed events, etc., you often want to capture the string name of a method. Using nameof helps keep your code valid when renaming definitions. Before you had to use string literals to refer to definitions, which is brittle when renaming code elements because tools do not know to check these string literals.

A nameof expression has this form:

if (x == null) throw new ArgumentNullException(nameof(x));
WriteLine(nameof(person.Address.ZipCode)); // prints "ZipCode”

关于c# - 如何在运行时获取方法的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32298850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com