Is there a way to make a region of code “read only” in visual studio?

泪湿孤枕 提交于 2019-12-10 17:54:40

问题


Every so often, I'm done modifying a piece of code and I would like to "lock" or make a region of code "read only". That way, the only way I can modify the code is if I unlock it first. Is there any way to do this?


回答1:


The easiest way which would work in many cases is to make it a partial type - i.e. a single class whose source code is spread across multiple files. You could then make one file read-only and the other writable.

To declare a partial type, you just use the partial contextual keyword in the declaration:

// MyClass.First.cs:
public partial class MyClass
{
    void Foo()
    {
        Bar();
    }

    void Baz()
    {
    }
}

// MyClass.Second.cs:
public partial class MyClass
{
    void Bar()
    {
        Baz();
    }
}

As you can see, it ends up as if the source was all in the same file - you can call methods declared in one file from the other with no problems.




回答2:


Compile it into into a library dll and make it available for reference in other projects.




回答3:


Split up the code into separate files and then check into a source control system?




回答4:


Given your rebuttal to partial classes... there is no way that I know of in a single file, short of documentation. Other options?

  • inheritance; but the protected code in the base-class (in an assembly you control); inheritors can only call the public/protected members
  • postsharp - stick the protected logic in attributes declared externally

However, both of these still require multiple files (and probably multiple assemblies).




回答5:


I thought about this, but I would prefer to keep the class in one file. – danmine

Sorry, mac. A bit of voodoo as a SVN pre-commit might catch it but otherwise no solution other than
// if you change this code you are fired




回答6:


This is totally unnecessary if you're using a version control system. Because once you've checked it in, it doesn't matter what part of the code you edit, you can always diff or roll back. Heck, you could accidentally wipe out all the source code and still get it back.

I'm getting a really bad "code smell" from the fact that you want to lock certain parts of the code. I'm guessing that maybe you're doing too much in one class, in which case, refactor it to a proper set of classes. The fact that, after the 10+ years visual studio has existed, this feature isn't available, should suggest that perhaps your desire to do this is a result of poor design.



来源:https://stackoverflow.com/questions/478135/is-there-a-way-to-make-a-region-of-code-read-only-in-visual-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!