How can I evaluate C# code dynamically?

后端 未结 16 1964
[愿得一人]
[愿得一人] 2020-11-22 03:37

I can do an eval(\"something()\"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I

16条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 04:18

    All of that would definitely work. Personally, for that particular problem, I would probably take a little different approach. Maybe something like this:

    class MyClass {
      public Point point1, point2, point3;
    
      private Point[] points;
    
      public MyClass() {
        //...
        this.points = new Point[] {point1, point2, point3};
      }
    
      public void DoSomethingWith(int i) {
        Point target = this.points[i+1];
        // do stuff to target
      }
    }
    

    When using patterns like this, you have to be careful that your data is stored by reference and not by value. In other words, don't do this with primitives. You have to use their big bloated class counterparts.

    I realized that's not exactly the question, but the question has been pretty well answered and I thought maybe an alternative approach might help.

提交回复
热议问题