c# - 是否可以在 C# 中创建扩展运算符?

标签 c#

所以基本的想法是:

我们有一些商业模式

public class Model
{
    public int Foo { get; set; }
}

它是 View 模型表示

public class ViewModel
{
    public string Foo { get; set; }

    public static explicit operator ViewModel(Model b)
    {
        // Map instances using AutoMapper or whatever
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

我们的基本本能是将模型映射到 View 模型。如您所见,我想使用 explicit operator 执行映射,所以我可以这样做

var model = new Model { Foo = 42 }; // Get model
var viewModel = (ViewModel)model;   // Map to view model

因此让我的 Controller 代码尽可能干净...但是我想让 View 模型和映射逻辑保持分离。如何将 explicit operator 实现移动到某个外部类?类似于扩展方法:

public static class Extensions
{
    public static explicit operator ViewModel(Model b)
    {
        // Map instances using Automapper or whatever
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

显然,这段代码无法编译,原因有二:
- 静态类不能包含用户定义的运算符
- 参数或返回类型必须是扩展

此外,作为一个选项,我可以使 View 模型成为部分 View 模型并拆分模型本身和运算符以分离 .cs 文件,但它不会成为现实。从架构上讲,它们仍然是同一命名空间中的同一类。我希望能够实现映射逻辑,例如,在解决方案的另一个项目中。

我只是想实现类似扩展方法的效果。我该怎么做?

最佳答案

没有比这更好的了:

public class ModelToViewModelMapper
{
    public ViewModel Map(Model b)
    {
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

扩展方法可以做同样的工作,但是如果你想改变映射逻辑怎么办。如果你使用依赖注入(inject)和非静态类,这将很容易

关于c# - 是否可以在 C# 中创建扩展运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32346482/

相关文章:

c# - 试图设置 VBO :s in C# using TAO and OpenGL TK framework

c# - 使用 FluentValidation 的 Release Build 得到错误

c# - 在我执行 ctrl+F5 之前,SignalR 在每隔一次页面刷新时中断

c# - 如何使用 System.Text.Json 将所有 `Nullable<T>` 值类型的空字符串反序列化为空值?

c# - 在方法调用之间缓存了哪些(如果有的话)本地定义的委托(delegate)?

c# - 从 dotnet 测试中排除命名空间

c# - 绕过我的头等待异步和 NHibernate

c# - 使用 WebClient 从 SharePoint Online 下载文件

c# - 在多个类之间共享变量

c# - asp.net mvc 5 GET 上的路由问题