如何检查一个对象是否具有某些方法/属性?

发布于 2024-10-19 07:20:02 字数 86 浏览 2 评论 0原文

也许使用动态模式?您可以使用动态关键字调用任何方法/属性,对吧?例如,如何在调用 myDynamicObject.DoStuff() 之前检查该方法是否存在?

Using dynamic pattern perhaps? You can call any method/property using the dynamic keyword, right? How to check whether the method exist before calling myDynamicObject.DoStuff(), for example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

回忆凄美了谁 2024-10-26 07:20:02

你可以写这样的东西:

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

编辑:你甚至可以做一个扩展方法并像这样使用它

myObject.HasMethod("SomeMethod");

You could write something like that :

public static bool HasMethod(this object objectToCheck, string methodName)
{
    var type = objectToCheck.GetType();
    return type.GetMethod(methodName) != null;
} 

Edit : you can even do an extension method and use it like this

myObject.HasMethod("SomeMethod");
回忆凄美了谁 2024-10-26 07:20:02

通过反射

 var property = object.GetType().GetProperty("YourProperty")
 property.SetValue(object,some_value,null);

类似的是方法

via Reflection

 var property = object.GetType().GetProperty("YourProperty")
 property.SetValue(object,some_value,null);

Similar is for methods

一张白纸 2024-10-26 07:20:02

这是一个老问题,但我刚刚遇到它。
如果有多个具有该名称的方法,Type.GetMethod(string name) 将抛出 AmbigeousMatchException,因此我们最好处理这种情况

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 

It is an old question, but I just ran into it.
Type.GetMethod(string name) will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case

public static bool HasMethod(this object objectToCheck, string methodName)
{
    try
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    }
    catch(AmbiguousMatchException)
    {
        // ambiguous means there is more than one result,
        // which means: a method with that name does exist
        return true;
    }
} 
分开我的手 2024-10-26 07:20:02

最好不要为此使用任何动态类型,并让您的类实现一个接口。
然后,您可以在运行时检查对象是否实现该接口,从而具有预期的方法(或属性)。

public interface IMyInterface
{
   void Somemethod();
}


IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
   x.Somemethod();
}

我认为这是唯一正确的方法。

您所指的是鸭子类型,这在您已经知道该对象具有该方法但编译器无法检查该方法的情况下非常有用。
例如,这在 COM 互操作场景中很有用。 (查看这篇文章)

例如,如果您想将鸭子类型与反射结合起来,那么我认为您是错过了鸭子打字的目标。

Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface.
Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).

public interface IMyInterface
{
   void Somemethod();
}


IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
   x.Somemethod();
}

I think this is the only correct way.

The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that.
This is useful in COM interop scenarios for instance. (check this article)

If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.

一笑百媚生 2024-10-26 07:20:02

为了避免 AmbigeousMatchException,我宁愿说

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0

To avoid AmbiguousMatchException, I would rather say

objectToCheck.GetType().GetMethods().Count(m => m.Name == method) > 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文