简体   繁体   English

在C#中编写静态和非静态方法时,如何避免出现“调用不明确……”错误?

[英]How do I avoid 'call is ambiguous…' error when writing static and non-static methods in C#?

I have a number of classes that represents business transaction calls: executing appropriate stored procedures. 我有许多表示业务交易调用的类:执行适当的存储过程。

Now the looks like this: 现在看起来像这样:

public static class Request
{
    public static void Approve(..) {
        using(connection) {
            command.Text = "EXEC [Approve] ,,"]
            command.ExecuteNonQuery();
        }
    }
}

And I want to make them more thread-safe: 我想使它们更加线程安全:

public class Request {
    public static void Approve(..) {
        new Request().Approve(..);
    }

    internal void Approve(..) {
        using(connection) {
            command.Text = "EXEC [Approve] ,,"]
            command.ExecuteNonQuery();
        }
    }
}

But getting next error message: 但是得到下一条错误消息:

The call is ambiguous between the following methods or properties: 'MyNamespace.Request.Approve(..)' and 'MyNamespace.Request.Approve(..)' 该调用在以下方法或属性之间是不明确的:“ MyNamespace.Request.Approve(..)”和“ MyNamespace.Request.Approve(..)”

How can I force, mark that I'm calling non-static, instance method from static? 如何强制标记我从静态调用非静态实例方法?

Or I cannot do that without renaming one of the methods? 还是不重命名其中一种方法就无法做到这一点? Or moving static method to another class, etc 或将静态方法移动到另一个类,等等

C# allows does not allow static methods to be called through instance references. C# 允许 不允许静态方法通过实例引用调用。 As such - the methods must either be named differently or use argument overloading to differentiate static methods from instance methods. 因此,方法必须命名不同或使用参数重载来区分静态方法和实例方法。

In your example, since the Approve() method is internal, renaming it is probably your easiest option. 在您的示例中,由于Approve()方法是内部方法,因此重命名它可能是您最简单的选择。

As to marking that a method is static ... I (personally) think the name is a perfectly good means to differentiate the two - why invent something more complicated. 至于标记一个方法是静态的...我(个人)认为该名称是区分两者的完美好方法-为什么要发明更复杂的方法。

If you're making a call from an instance (eg requestVar.Approve() ), then no, you have to rename it. 如果要从实例(例如requestVar.Approve() )进行调用,则不能,您必须重命名它。 The static can be called by using Request.Approve() however. 可以通过使用Request.Approve()来调用静态方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM