Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

C# call abstract method from static method

i am writing library, that can be used for with different database engines. Abstract class has abstract DbParameter constructor and uses classes from System.Data.Common.

Now i have sutch structure :

public abstract class ASqlWorker{

 abstract protected DbParameter DbParameterConstructor(String paramName, Object paramValue);

}

now, can i call abstract DbParameterConstructor from a static method of ASqlWorker?

Logicaly, i could make abstractMethod static (it creates instance of an inheriter of DbParameter from name and value and doesn't use fields of ASqlWorker), but it is not allowed in C#. btw, it is not allowed because of usage of non-realised static method can cause troubles. But in my case it won't, because my abstract method is protected.

i just want to write some implicit convertor from DbParameter to new DbParameter[1] to have more flexible interfaces.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your question assumes you could call a method on an abstract "instance" and we all know that is not possible, however if a subclass was defined and you were calling the abstract defined method on an instance of the concrete implementation of the abstract base class then the answer is yes. But the point here is you must call an instance method on an instance.

This is possible:

ASqlWorker a = new SubClassesASqlWorker();  //<-- assume you extending ASqlWorker and implemented it

This is not possible:

ASqlWorker a = new ASqlWorker();

You could define your static method with a parameter of the abstract type but you can only pass it objects that are fully implemented and a subclass of the abstract class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...