.NET - 显示/隐藏基于使用的构造函数的方法?

Sax*_*man 2 .net c# constructor

如果使用某个构造函数,有没有办法隐藏/显示方法?即:

public class SomeClass
{
    public SomeClass(string methodA)
    {

    }

    public SomeClass(int methodB)
    {

    }

    public string MethodA()
    {
        return "";
    }

    public int MethodB()
    {
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果SomeClass(string methodA)使用,那么只有MethodA()在我实例化新SomeClass对象时才可用?使用时相同SomeClass(int methodB),那么MethodB()可用吗?

谢谢你们!

Ser*_*rvy 5

不,这是不可能的.

更有可能的是你想使用泛型:

public interface IFoo<T>
{
    T Method();
}

public class IntFoo : IFoo<int>
{
    int value;
    public IntFoo(int value)
    {
        this.value = value;
    }

    public int Method()
    {
        return value;
    }
}

public class StringFoo : IFoo<string>
{
    string value;
    public StringFoo(string value)
    {
        this.value = value;
    }

    public string Method()
    {
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你不需要将它限制为字符串或整数(或者不想),那么这样的东西可能会起作用,甚至更好:

public class Foo<T>
{
    private T value;
    public Foo(T value)
    {
        this.value = value;
    }

    public T Method()
    {
        return value;
    }
}
Run Code Online (Sandbox Code Playgroud)