Preprocessor directives across different files in C#

后端 未结 4 1677
我在风中等你
我在风中等你 2020-12-06 11:00

I know that I can use preprocessor directives in C# to enable/disable compilation of some part of code.

If I define a directive in the same file, it wor

4条回答
  •  孤街浪徒
    2020-12-06 11:30

    Instead of adding conditional compilation to your files, and adding blocks of code which use Linq, and others, which don't. I'd moved all data-access logic (i.e. code which have two implementations - with Linq and without) to separate libraries.

    E.g. create interfaces, which your main application will use. And create two implementations of those interfaces - one which use Linq, and another which don't use:

    In main project:

    public interface IUserRepository
    {
        IEnumerable GetUsersByCompanyName(string companyName);
    }
    

    In Persistence.Linq.dll :

    using System.Linq; 
    
    public class UserRepository : IUserRepository
    {
        public IEnumerable GetUsersByCompanyName(string companyName)
        // use Linq here
    }
    

    In Persistence.SomethingOther.dll:

    public class UserRepository : IUserRepository
    {
        public IEnumerable GetUsersByCompanyName(string companyName)
        // do not use Linq here
    }
    

    Now you can inject any implementation of IUserRepository into your main application classes.

提交回复
热议问题