gpt4 book ai didi

c# - 使用 Composition 在 C# 中自动生成 Wrapper 类

转载 作者:可可西里 更新时间:2023-11-01 09:13:52 25 4
gpt4 key购买 nike

这应该很简单,但我找不到任何东西。

我在一个程序集中有一个类(一个共享库——它是一组 Web 服务的代理类)我在另一个程序集(Web 项目)中有一个类

Proxy 程序集中有一个名为“Profile”的类。在 Web 项目中有一组“使用”配置文件的类。当没有用户登录时,使用 GenericProfile。

遵循“关注点分离”的原则......代理程序集由其他项目使用,只与 Web 服务有关。web 项目里面只有 web 的东西

但是,现在需要“GenericProfile”——将其视为“Guest User”。

合乎逻辑的做法是构建一个名为 IProfile 的接口(interface),并使两个类都从它派生。但这会在两个程序集之间产生循环依赖。

下一个最佳想法是创建一个名为 MyInterfaces 的第三个程序集并将 IProfile 放在那里——但在我看来,这会导致违反关注点分离原则。至少,这个问题的一个实例似乎不足以成为在我的解决方案中制作额外模块的理由。

输入包装器类——或复合包装器类(随便你怎么调用它)

我正在寻找最终会生成如下所示内容的内容。是否有工具或 Visual Studio 扩展可以做到这一点?也许是 .tt 文件?

namespace WebProject
{
public interface IProfile
{...}

class MyWrapperClass : IProfile
{
Proxy.Profile _profile;

public MyWrapperClass(Proxy.Profile proxy)
{
_profile = proxy;
}

public string IProfile.Property1{ get { return _profile.Property1; } set { _profile.Property1 = value; } }
public string IProfile.Property2{ get { return _profile.Property2; } set { _profile.Property2 = value; } }
public string IProfile.Property3{ get { return _profile.Property3; } set { _profile.Property3 = value; } }
}

}

最佳答案

在 Visual Studio 2017 中

创建你的类

namespace WebProject
{
public interface IProfile
{...}

class MyWrapperClass : IProfile
{
private IProfile _wrapped;
}
}

将光标定位在类 MyWrapperClass 的 IProfile 上:IProfile 并按 ctrl-。选择通过_wrapped 实现接口(interface)。不需要 ReSharper。

关于c# - 使用 Composition 在 C# 中自动生成 Wrapper 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7252255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com