C# 中使用隐式和显式操作符的示例

这篇文章主要介绍了C# 中使用隐式和显式操作符的示例,帮助大家更好的理解和学习使用c#,感兴趣的朋友可以了解下

人工干预后,编译器也就放行了。

创建 DTO 类

接下来我们研究一下如何在 用户自定义类型 上使用 隐式 和 显式转换,比如:Class,考虑下面的类。


    public class Author
    {
        public Guid Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class AuthorDto
    {
        public string Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

在上面的代码中,定义了一个 Author 实体类,然后再为 Author 定义一个数据传输对象 AuthorDTO,数据传输对象是一个数据容器,常用于在 Presentation 和 Application层 之间传递数据。

Model 和 DTO 之间的相互转换

下面的代码展示了如何实现 Author 和 AuthorDto 之间的相互转换。


        public AuthorDto ConvertAuthorToAuthorDto(Author author)
        {
            AuthorDto authorDto = new AuthorDto
            {
                Id = author.Id.ToString(),
                FirstName = author.FirstName,
                LastName = author.LastName
            };
            return authorDto;
        }

        public Author ConvertAuthorDtoToAuthor(AuthorDto authorDto)
        {
            Author author = new Author
            {
                Id = Guid.Parse(authorDto.Id),
                FirstName = authorDto.FirstName,
                LastName = authorDto.LastName
            };
            return author;
        }

如果需要在应用程序中为若干个类写这样的转换代码,你会发现实现类之间的转换使的代码比较冗余,而且代码可读性也好不到哪里去。所以在这种场景下就是 显式 和 隐式 操作符的用武之地。

使用隐式操作符

实现 model-dto 之间的转换更简单粗暴的方式就是使用 隐显式操作符,这样就避免了冗长的方法调用,让代码更加的直截了当。

下面的代码展示了如何使用 隐式操作符 将 Author实例 转成 AuthorDto 实例。


public static implicit operator AuthorDto(Author author)
{
  AuthorDto authorDto = new AuthorDto();
  authorDto.Id = author.Id.ToString();
  authorDto.FirstName = author.FirstName;
  authorDto.LastName = author.LastName;
  return authorDto;
}

接下来看一下如何在 Main 方法中使用 隐式操作符。


static void Main(string[] args)
{
   Author author = new Author();
   author.Id = Guid.NewGuid();
   author.FirstName = "Joydip";
   author.LastName = "Kanjilal";
   AuthorDto authorDto = author;
   Console.ReadKey();
}

使用显式操作符

下面的代码展示了如何利用 显式操作符 将 Author 实例转成 AuthorDto 。


public static explicit operator AuthorDto(Author author)
{
  AuthorDto authorDto = new AuthorDto();
  authorDto.Id = author.Id.ToString();
  authorDto.FirstName = author.FirstName;
  authorDto.LastName = author.LastName;
  return authorDto;
}

这时候在 Main 方法中就需要人工介入进行强转了,如下代码所示:


static void Main(string[] args)
{
  Author author = new Author();
  author.Id = Guid.NewGuid();
  author.FirstName = "Joydip";
  author.LastName = "Kanjilal";
  AuthorDto authorDto = (AuthorDto)author;
  Console.ReadKey();
}

值得注意的是,你不能在一个类中的对象转换同时定义 显式 和 隐式操作符,如下图所示:

如果你定义了隐式操作符,那么对象之间的转换可以是隐式或显式,如果你定义了显式操作符,那么你只能显式的实现对象转换,虽然隐式操作使用起来非常方便,但显式操作会让代码意图更明显,可读性更高。

以上就是C# 中使用隐式和显式操作符的示例的详细内容,更多关于C# 中使用隐式和显式操作符的资料请关注得得之家其它相关文章!

本文标题为:C# 中使用隐式和显式操作符的示例