c#封装了项目引用

  • 本文关键字:引用 项目 封装 c#
  • 更新时间 :
  • 英文 :


假设我有项目P1, P2和P3。

P2引用P1,它的类使用P1的类。同时P3引用P2,它的类使用P2的类,而P2的类又使用P1的类。

要使其工作,我需要在P3中引用P1和P2。是否有任何方法可以将P1的类封装到P2(因此P3只需要引用P2)?

可能是因为你的项目P3使用了P1的类型?因为在下面的例子中,当P2类型在内部使用P1的类型时,一切都工作得很好。或者只是另一种选择:您可以将公共模型提取到单独的库中。

假设下一个是P1

public class P1_Model {
    public string Name {
        get { return "1"; }
    }
}
public class P1_Service {
    public static P1_Model Execute() {
        return new P1_Model();
    }
}

和P2

public class P2_Service {
    public static P2_Model Execute() {
        var p1Model = P1_Service.Execute();
        return new P2_Model(p1Model);
    }
    public class P2_Model {
        public P2_Model(P1_Model p1Model) {
            Model = p1Model;
        }
        public string Name {
            get { return Model.Name; }
        }
        public P1_Model Model { get; }
    }
}

P3

var p2Model = P2_Service.Execute();
Console.WriteLine(p2Model.Name); //works fine. No Reference to P1 needed
Console.WriteLine(p2Model.Model.Name); // requires P1 reference from P3

根据您的确切需求,您还可以考虑使用ILMerge将多个程序集合并为一个程序集。

您不必在p3中引用p1,因为只有p2使用p1的类。您只需要在项目中部署p1库和p2库。大多数情况下,visual studio会为你做这些。你只需要在p3中引用p2就可以了。

最新更新