Visual Studio: Exclude a class if compiling as a d

2019-08-07 14:23发布

I have a DLL project that I often compile as a .exe so that I can easily test the classes in it. One class contains a Main() method, which is useless when I compile it as a .dll file. I would like to automatically exclude this class from the project whenever I am compiling it as a class library. It seems like I must be one of the first people to run into this problem, as the almighty Google doesn't seem to have an answer for my question: How do I do this?

2条回答
乱世女痞
2楼-- · 2019-08-07 14:45

You have a couple of solutions that I can think of:

1) Use conditional compiler options. For example, only include it if it is in debug

#if DEBUG

public void Main() {  
// Do Stuff  
}  

#endif

2) Make the Main method internal, or move it into a test project you can run. Then you either use it directly, or ensure that your test DLL can see the internal methods.

3) Move the Main method out into a completely different .exe that references the original DLL. (This is similar to option 2 without using a test framework).

查看更多
Root(大扎)
3楼-- · 2019-08-07 14:50

I would seriously consider unit testing as apose to doing this constantly. Even if unit testing isn't implemented properly and you just use it as an intermediate debugger. I would even go as far as saying do a unit test project as apose to a console application for debugging your code, in terms of getting access it will make your life a lot easier and in the future if you wish to implement some form of unit testing you can.

[TestMethod]
public class YourClassNameTests
{
  public T YourObject;
  [TestInitialize()]
  public void Initializer()
  {
    YourObject = new T();
  }
  [TestMethod()]
  public void YourMethodTest()
  {
    //Arrange
    YourObject.ReliantProperty = 1;
    //Act
    var objResult = YourObject.YourMethod();
    //Assert
    Assert.IsTrue(objResult == 1);
  }
}
查看更多
登录 后发表回答