C#封装项目引用

时间:2015-08-06 04:04:22

标签: c#

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

P2引用了P1,它的类使用P1的类。同时P3引用了P2,它的类使用P2的类,这些类使用P1的类。

为了使其工作,我需要在P3中引用P1和P2。有没有办法将P1的类封装到P2(所以P3只需要引用P2)?

3 个答案:

答案 0 :(得分:2)

可能是因为您的项目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

答案 1 :(得分:0)

根据您的确切需求,您还可以考虑使用ILMerge将多个装配合并到一个装配中。

答案 2 :(得分:0)

你不必在p3中引用p1,因为只有p2使用p1的类。您只需在项目中使用p2部署p1库。 大部分时间,visual studio都会为您完成。你只需要在p3中使用参考p2,一切都可以完成。