首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

是否有一个C#等同于Ruby的`respond_to?`?

在C#中,没有一个直接等同于Ruby中的respond_to?的方法,但是可以使用System.Reflection.MethodBase.GetMethodFromHandle方法从MethodHandle对象中获取方法信息,然后使用System.Reflection.MethodBase.Invoke方法调用该方法。虽然这种方法与respond_to?在Ruby中的工作方式不同,但可以实现类似的功能。

以下是一个示例代码,它使用System.Reflection.MethodBase.GetMethodFromHandle方法从MethodHandle对象中获取方法信息,然后使用System.Reflection.MethodBase.Invoke方法调用该方法:

代码语言:csharp
复制
using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        // 获取MethodHandle对象
        MethodHandle methodHandle = GetType().GetMethod("TestMethod").MethodHandle;

        // 获取MethodBase对象
        MethodBase methodBase = methodHandle.Method;

        // 调用MethodBase对象
        object result = methodBase.Invoke(null, null);

        // 输出结果
        Console.WriteLine("Result: " + result);
    }

    public static void TestMethod()
    {
        Console.WriteLine("TestMethod is called.");
    }
}

在上面的示例代码中,我们首先使用GetType().GetMethod("TestMethod").MethodHandle获取TestMethod方法的方法句柄,然后使用MethodBase.GetMethodFromHandle方法从该句柄中获取方法信息,并使用MethodBase.Invoke方法调用该方法。最后,我们输出调用结果。

虽然这种方法与respond_to?在Ruby中的工作方式不同,但可以实现类似的功能。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券