Manual editing of *.designer.cs file

前端 未结 5 1358
时光取名叫无心
时光取名叫无心 2020-11-28 16:29

I\'m aware, that the .designer.cs file contains data generated by the visual form designer in Visual Studio. However, I have some additional methods though, whi

5条回答
  •  天命终不由人
    2020-11-28 17:16

    I think the other answers are simplifying too much.

    First of all, I totally agree that it's almost always a bad idea to edit a .designer file, but there are a few cases where I've done so, feel it was good and proper, and didn't get burned.

    1. Say I create a label and accidentally double click. Designer creates a method in my main .cs file which I then delete:

      private void label1_Click(object sender, EventArgs e)
      {
      
      }
      

      Well, now the code won't build unless I also delete the following from my .designer file:

      this.label1.Click += new System.EventHandler(this.label1_Click);
      
    2. Less frequently, the order in which things are added to a form or panel (or menu!) matters, and it can be easier to change this order in the code than in the Designer GUI. In my experience VS 2010 always picks up on this, updates its GUI's info, and redraws its preview. Just remember to focus on the Add() methods--the order variables are declared in generally doesn't matter.

    3. Ditto if you set a property that causes a line to be added to the .designer file, deleting the line gets picked up quickly and Designer refreshes. Maybe it's wiser/safer to use the GUI to change the property, but I think deleting the line is cleaner.

    4. Code that is not inside this region, #region Windows Form Designer generated code, will only get generated once. It is safe to move, and as others have recommended elsewhere (https://stackoverflow.com/a/6527072/1593924), moving the Dispose(bool) method out actually can make a lot of sense, if you're modifying it or adding a Dispose() method that should ideally sit next to Dispose(bool).

      protected override void Dispose(bool disposing)
      {
          if (disposing && (components != null))
          {
              components.Dispose();
          }
          base.Dispose(disposing);
      

    DISCLAIMERS:

    1. That said, I've only tried VS 2010 Ultimate; your mileage may vary on 1-3 above, but 4 should be safe as long as the .designer is a partial class with Dispose(bool) outside that #region. I also make sure the latest good version of a .designer file is committed into the source repository before messing with it.

    2. By admitting to having gone along with the Dispose(bool disposing) pattern, I'm not meaning to promote that approach. There seem to be good reasons to simply use Dispose() in most cases, and only do more for unmanaged resources, each of which is encapsulated one-to-one in a dedicated Disposable object.

提交回复
热议问题