C# virtual static method

2019-01-22 06:09发布

Why is static virtual impossible? Is C# dependent or just don't have any sense in the OO world?

I know the concept has already been underlined but I did not find a simple answer to the previous question.

9条回答
太酷不给撩
2楼-- · 2019-01-22 06:44

To summarize all the options presented:

查看更多
Anthone
3楼-- · 2019-01-22 06:45

Eric Lippert has a blog post about this, and as usual with his posts, he covers the subject in great depth:

http://blogs.msdn.com/b/ericlippert/archive/2007/06/14/calling-static-methods-on-type-parameters-is-illegal-part-one.aspx

“virtual” and “static” are opposites! “virtual” means “determine the method to be called based on run time type information”, and “static” means “determine the method to be called solely based on compile time static analysis”

查看更多
放我归山
4楼-- · 2019-01-22 06:53

Yes it is possible.

The most wanted use case for that is to have factories which can be "overriden"

In order to do this, you will have to rely on generic type parameters using the F-bounded polymorphism.

Example 1 Let's take a factory example:

class A: { public static A Create(int number) { return ... ;} }
class B: A { /* How to override the static Create method to return B? */}

You also want createB to be accessible and returning B objects in the B class. Or you might like A's static functions to be a library that should be extensible by B. Solution:

class A<T> where T: A<T> { public static T Create(int number) { return ...; } }
class B: A<B>  { /* no create function */ }
B theb = B.Create(2);       // Perfectly fine.
A thea = A.Create(0);       // Here as well

Example 2 (advanced): Let's define a static function to multiply matrices of values.

public abstract class Value<T> where T : Value<T> {
  //This method is static but by subclassing T we can use virtual methods.
  public static Matrix<T> MultiplyMatrix(Matrix<T> m1, Matrix<T> m2) {
    return // Code to multiply two matrices using add and multiply;
  }
  public abstract T multiply(T other);
  public abstract T add(T other);
  public abstract T opposed();
  public T minus(T other) {
    return this.add(other.opposed());
  }
}
// Abstract override
public abstract class Number<T> : Value<T> where T: Number<T> {
  protected double real;

  /// Note: The use of MultiplyMatrix returns a Matrix of Number here.
  public Matrix<T> timesVector(List<T> vector) {
    return MultiplyMatrix(new Matrix<T>() {this as T}, new Matrix<T>(vector));
  }
}
public class ComplexNumber : Number<ComplexNumber> {
  protected double imag;
  /// Note: The use of MultiplyMatrix returns a Matrix of ComplexNumber here.
}

Now you can also use the static MultiplyMatrix method to return a matrix of complex numbers directly from ComplexNumber

Matrix<ComplexNumber> result = ComplexNumber.MultiplyMatrix(matrix1, matrix2);
查看更多
Animai°情兽
5楼-- · 2019-01-22 06:55

While technically its not possible to define a static virtual method, for all the reasons already pointed out here, you can functionally accomplish what I think your trying using C# extension methods.

From MSDN:

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Check out C# Extension Methods (C# Programming Guide) for more details.

查看更多
疯言疯语
6楼-- · 2019-01-22 06:59

Guys who say that there is no sense in static virtual methods. If you don't understand how this could be possible, it does not means that it is impossible. There are languages that allow this!! Look at Delphi, for example.

查看更多
【Aperson】
7楼-- · 2019-01-22 07:00

I'm going to be the one who naysays. What you are describing is not technically part of the language. Sorry. But it is possible to simulate it within the language.

Let's consider what you're asking for - you want a collection of methods that aren't attached to any particular object that can all be easily callable and replaceable at run time or compile time.

To me that sounds like what you really want is a singleton object with delegated methods.

Let's put together an example:

public interface ICurrencyWriter {
    string Write(int i);
    string Write(float f);
}

public class DelegatedCurrencyWriter : ICurrencyWriter {
    public DelegatedCurrencyWriter()
    {
        IntWriter = i => i.ToString();
        FloatWriter = f => f.ToString();
    }
    public string Write(int i) { return IntWriter(i); }
    public string Write(float f) { return FloatWriter(f); }
    public Func<int, string> IntWriter { get; set; }
    public Func<float, string> FloatWriter { get; set; }
}

public class SingletonCurrencyWriter {
    public static DelegatedCurrencyWriter Writer {
        get {
            if (_writer == null)
               _writer = new DelegatedCurrencyWriter();
            return _writer;
        }
    }
}

in use:

Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400.0

SingletonCurrencyWriter.Writer.FloatWriter = f => String.Format("{0} bucks and {1} little pennies.", (int)f, (int)(f * 100));

Console.WriteLine(SingletonCurrencyWriter.Writer.Write(400.0f); // 400 bucks and 0 little pennies

Given all this, we now have a singleton class that writes out currency values and I can change the behavior of it. I've basically defined the behavior convention at compile time and can now change the behavior at either compile time (in the constructor) or run time, which is, I believe the effect you're trying to get. If you want inheritance of behavior, you can do that to by implementing back chaining (ie, have the new method call the previous one).

That said, I don't especially recommend the example code above. For one, it isn't thread safe and there really isn't a lot in place to keep life sane. Global dependence on this kind of structure means global instability. This is one of the many ways that changeable behavior was implemented in the dim dark days of C: structs of function pointers, and in this case a single global struct.

查看更多
登录 后发表回答