C#: Creating an instance of an abstract class without defining new class

前端 未结 9 750
眼角桃花
眼角桃花 2020-12-29 04:25

I know it can be done in Java, as I have used this technique quite extensively in the past. An example in Java would be shown below. (Additional question. What is this techn

相关标签:
9条回答
  • 2020-12-29 05:20

    You are able to accomplish this with Mocking in .NET. However there is no in-language support for this feature, I think it will be available in C# 4.0. There are a number of libraries out there for Mocking, including:

    • Moq
    • RhinoMock
    0 讨论(0)
  • 2020-12-29 05:21

    In short no, you have to define it as separate sub class. I think this feature is coming C# 4.0 though?

    Edit: No it's not coming C# 4.0 I made that up.

    0 讨论(0)
  • 2020-12-29 05:24

    Typically, problems that are solved with anonymous inner classes in Java are solved in a much cleaner fashion using delegates in .Net. Your example is a little too simplistic to determine your intent. If your intent by using the abstract class is to pass around a "behavior" think about just using an Action delegate instead.

    public class StartHere{
       public static void main(string[] args){
          Action doStuff = () => Console.WriteLine("Did stuff");
          executeSomething(doStuff);
       }
    
       public static void executeSomething(Action action)
       {
          action();
       }
    }
    
    0 讨论(0)
提交回复
热议问题