ToString()和 implicit operator string的区别

Unity游戏开发:Protobuf-net与Google.Protobuf性能对比与实战集成指南 数据序列化是网络通信与数据持久化的核心技术,它决定了数据交换的效率和体积。其原理是将数据结构或对象状态转换为可存储或传输的格式,反序列化则是其逆过程。这项技术的核心价值在于提升传输速度、减少带宽占用并确保跨平台数据一致性,对于网络游戏、微服务通信和配置管理等场景至关重要。在Unity开发中,面对网络同步、存档等需求,开发者常需在便捷与标准化间权衡。本文聚焦于Protocol Buffers这一高效序列化方案,深入对比基于特性的Protobuf-net与基于.proto文件的Google.Protobuf两种 阅读详情

写这篇文章是来源于一次关于Cast和ConsoleWriteline()的研究。

ConsoleWriteline()是一个在终端输出的简单方法,但是它输出原理是什么?下面给出一个例子。

    public struct Currency
    {
        public uint Dollars { get; }
        public ushort Cents { get; }

        public Currency(uint dollars, ushort cents)
        {
            Dollars = dollars;
            Cents = cents;
        }
        
        public override string ToString() => $"${Dollars}.{Cents,-2:00}";
        public static implicit operator string (Currency value) => "Currency";
   }

先看ToString()和 public static implicit operator string (Currency value) => “Currency”; 第 一个是重写方法,第二个是隐式转换。
那么调用以下代码输出

                Currency balance = new Currency(50, 35); 
                Console.WriteLine(balance);
                Console.WriteLine($"balance is {balance}");

输出结果
在这里插入图片描述
可以看出第一个writeline调用了隐式转换,第二个writeline 调用了ToString()方法。
所以其中隐含的代码应该是这样的

                Console.WriteLine((string)balance);
                Console.WriteLine($"balance is {balance.ToString()}");

但是如果注释掉隐式转换//public static implicit operator string (Currency value) => “Currency”;
输出结果就变成了:
在这里插入图片描述
如果注释掉ToString()//public override string ToString() => """{Dollars}.{Cents,-2:00}";
输出结果就变成了:
在这里插入图片描述

所以这里揭示了两个规则,第一,隐式转换优先级高于ToString()方法,WriteLine(balance)先检查隐式转换符是否存在,如果不存在则调用ToString()方法。第二,$相当于String.Format()简化,String.Format()里面的参数并不会调用隐式转换,而是直接调用ToString()方法,由于重写方法被注释,所以调用了默认的ValueType.ToString()方法,。

C#中非IEnumerable集合如何使用LINQ:四种实战方案对比 LINQ扩展方法本质上是面向IEnumerable<T>或IQueryable<T>的契约式工具,其调用依赖编译期类型匹配而非运行时行为。当自定义集合(如DDD聚合根、DTO容器)未实现IEnumerable<T>时,.Where()等方法即失效——这并非语法限制,而是类型系统对数据可枚举性的显式要求。理解这一原理,才能合理选择适配路径:显式转换适用于临时调试与内存计算;隐式转换虽简洁但易触发序列化副作用;扩展方法注入在封装性与性能间取得最佳平衡,支持内联优化且零内存分配;查询对象模式则面向复杂条件组合与C 阅读详情

相关推荐

菜鸟之隐式转换(implicit)、显示转换(explicit)及转换函数(operator()const)

学习C++过程中,遇到很多数据类型的转换

u010273604的专栏 2193

.NET XML序列化实战:命名空间、CDATA与DateTime处理指南

XML序列化是结构化数据交换的基础技术,其核心在于严格遵循XML Schema(XSD)、精确控制命名空间、保障类型语义一致性,并支持可验证的文档结构。相比JSON,XML在工业协议(如IEC 61850)、金融清算、政务对接等强契约场景中不可替代,关键价值体现在xsi:type、xml:lang、CDATA节、默认命名空间声明等细节的可控性上。技术实现需深入理解XmlSerializer的编译时代码生成机制、XmlSerializerNamespaces对前缀的精准绑定,以及DateTime时区格式、CD

lanmh的专栏 638

Vivado静态时序分析学习笔记(1)

静态时序分析分为片内时序分析(寄存器与寄存器之间的时序关系)和片外时序分析(IO时序分析)。(1)建立时间 setup time在时钟事件(上升沿/下降沿)发生之前数据信号应保持稳定的时间。把实际电路抽象成前级D触发器+组合逻辑+后级D触发器。

Fantaasky的博客 4375

c#自定义类型的转换方式operator,以及implicit(隐式)和explicit (显示)声明的区别...

msdn参考:http://msdn.microsoft.com/zh-cn/library/s53ehcz3.aspx http://msdn.microsoft.com/zh-cn/library/z5z9kes2.aspx http://msdn.microsoft.com/zh-cn/library/xhbhezf4.aspx ...

weixin_33738982的博客 341

告别抓包失败!保姆级配置:让Burp+Proxifier稳定抓取任意微信小程序

本文提供了一套完整的Burp+Proxifier配置方案,确保稳定抓取微信小程序数据。从环境准备、工具选型到Burp Suite深度配置和Proxifier精准设置,详细解决了证书安装、进程捕获和乱码解析等核心问题,帮助开发者告别抓包失败,提升调试效率。

weixin_28738165的博客 451

RI-CLPM vs CLPM:什么时候该用随机截距交叉滞后模型?

本文深入对比了交叉滞后模型(CLPM)与随机截距交叉滞后模型(RI-CLPM)的核心差异与应用场景。RI-CLPM通过分离个体间稳定特质与个体内动态波动,能更纯净地估计变量间的动态因果关系,避免CLPM可能存在的混淆。文章提供了清晰的模型选择决策框架,并辅以Mplus语法示例,帮助研究者根据变量特质稳定性与研究问题,正确选用模型以确保结论的严谨性。

weixin_29276847的博客 302

【转】 C# :operator、explicit与implicit

C# 参考之转换关键字:operator、explicit与implicitoperatoroperator 关键字用于在类或结构声明中声明运算符。运算符声明可以采用下列四种形式之一:  public static result-type operator unary-operator ( op-type operand ) public static re

573

scRNA-seq | 吐血整理的单细胞入门教程(从原理到代码实操)(二)

scRNA-seq | 吐血整理的单细胞入门教程(从原理到代码实操)(二)

m0_72224305的博客 4305

.net 隐式自定义类型转换运算符 static implicit operator

public static implicit operator T1(T2 t) static implicit operator static implicit operator static implicit operator

lwpoor123的博客 991

C# 的 Dapper 库高级进阶:刨根问底的深度解析

通过今天的探索,我们了解了 Dapper 的一些高级功能,包括如何处理复杂的查询、执行批量操作以及如何优化性能。希望这篇深入浅出的文章能帮助你在实际项目中更好地运用 Dapper!🎈好了,小伙伴们,今天的分享就到这里啦!如果你有任何疑问或者想要分享自己的经验,请在评论区留言。我们下次再见!👋上述示例代码仅供参考,实际使用时请根据项目需求进行适当调整。✨Dapper 官方文档Dapper 性能优化指南Dapper 动态参数使用来同时执行多个查询。利用Execute和Query方法来简化 SQL 调用。

java专栏 812

MicroCap声学仿真介绍(二)-创建声学仿真元件

声学库里包含孔、管、障板辐射器等器件,我们只需要按照仿真的需求,将声学库里的器件排列好,输入参数,用线连接起来即可。这里我们用D指代孔的直径,L指代孔的长度,N代表孔的数量。26.在弹出的界面中做如下设置:需要先在右面的选框里找到对应的项,然后右键Add Part,再之后就如下设置。3.在弹出的界面中,选择“Macro file(.mac)”,并点击右上角的“OK”下面就以声学仿真中常见的“孔”来做示例,跟大家一块演示一下宏程序的新建。10.在上图中“Value”中填入“R”,然后点击左边的“OK”按钮;

山无忧的博客 2195

Operator运算符重载与Implicit隐式类型转换

class Person { public int Age { get; set; } public string Name { get; set; } public static int operator -(Person p1, Person p2)//int为想减结果类型,-表示对-进行运算符重载 //参数为待计算的两个值 {

@ 2518

SAP PCE 到底有没有 AI 能力:从标准功能、Joule、ABAP 扩展到项目落地的完整解读

摘要:SAP S/4HANA Cloud Private Edition(PCE)已深度集成AI能力,主要体现在三个方面:1)标准业务流程中的AI辅助功能(如财务分录生成、维修单据处理);2)通过Joule提供的自然语言交互入口,支持业务导航和部分事务处理;3)开发者可通过ABAP AI SDK与BTP平台集成实现扩展。PCE不是独立AI平台,企业级自定义AI需结合SAP BTP实现。AI能力已深度融入财务、制造等业务场景,但关键业务仍需人工审核。(149字)

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 330

c#自定义类型的转换方式operator,以及implicit(隐式)和explicit (显示)声明的区别

原文链接using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 自定义装换 { class Program { static void Main(string[] args) { mycla...

PalmAdorableTiger的博客 3016

AI Agent的数据安全与隐私保护措施

AI Agent(人工智能代理)作为一种能够感知环境、做出决策并采取行动的智能实体,在现代社会的各个领域中得到了广泛的应用,如智能客服、自动驾驶、金融风险评估等。随着其应用的不断拓展,AI Agent处理和存储的数据量急剧增加,这些数据包含了大量的个人敏感信息和商业机密。因此,确保AI Agent的数据安全与隐私保护变得至关重要。本文的目的在于全面探讨AI Agent的数据安全与隐私保护措施,涵盖从数据的采集、存储、处理到传输的整个生命周期。

AGI×大数据,开启智能时代的认知跃迁;解码AGI,赋能数据驱动的智能革命。 2864

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

C++初始化列表与隐式类型转换:核心机制解析与工程实践

在C++编程中,对象构造与类型转换是影响代码性能与安全性的基础机制。初始化列表决定了成员变量的初始化方式,确保对象在构造函数体执行前就处于确定状态,这对于const成员、引用成员及无默认构造函数的类成员至关重要。隐式类型转换则通过转换构造函数和类型转换运算符实现类型间的自动转换,虽能简化代码,但可能引发意外的函数重载解析、临时对象创建及逻辑错误。理解这些原理有助于编写更高效、健壮的代码,尤其在资源管理、接口设计等场景中。本文通过智能指针等案例,深入探讨了初始化列表的正确使用、隐式转换的风险控制(如expli

weixin_33868027的博客 420

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

C标准库详解:从csharpstandard项目看ECMA规范中的类库定义

C#标准库是ECMA C#规范的核心组成部分,它定义了C#语言必须支持的基础类型和成员。通过深入分析csharpstandard项目中的标准文档,我们可以清晰了解C#类库的规范定义和设计理念。本文将带你探索ECMA规范中类库的核心结构、关键类型和使用要点,帮助开发者更好地理解和应用C#标准库。 ## C#标准库的基础架构与规范 C#标准库作为ECMA规范的一部分,定义了语言实现必须提供的最小类

gitblog_00283的博客 489

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

C#笔记################################################################################################

‌

Jesui的博客 886

Scala运算符本质:方法调用、中缀语法与DSL构建原理

在编程语言中,'运算符'常被误解为语法糖或编译器特例,但其本质是类型系统与方法调用机制的外化表达。从Java的固定语义到Scala的全开放方法协议,运算符演变为可重载、可组合、支持类型推导的语义载体。核心原理在于:所有符号(如+、::、===)均映射为普通方法,遵循标识符命名规则与基于首字符的优先级体系,并通过中缀调用实现自然语言式表达。这种设计支撑了Spark DSL的类型安全列操作、Cats函数式效果类型(如|+|、>>=)及领域专用语法构建。对Scala开发者而言,理解运算符即理解如何让代码语义精准贴

weixin_34327223的博客 420

operator,implicit(隐式)和explicit (显示)转换

c#自定义类型的转换方式operator,implicit(隐式)和explicit (显示)声明 operator 关键字来重载内置运算符,或提供类或结构声明中的用户定义转换。它可以定义不同类型之间采用何种转化方式和转化的结果。 operator用于定义类型转化时可采用2种方式,隐式转换(implicit)和显示转换(explicit) public static implicit 目标类...

chendandan的博客 3017

自定义隐式转换和显式转换c#简单例子

自定义隐式转换和显式转换c#简单例子 (出自朱朱家园http://blog.youkuaiyun.com/zhgl7688) 例子:对用户user中,用户名first name和last name进行转换成合成一个限定长度为10个字符新name。 自定义隐式转换: namespace transduction { public partial class transductionForm :

朱朱家园 3738

c# 自定义隐式转换与运算符重载

c# 自定义隐式转换与运算符重载

anlog的专栏 954
上一篇: C#为什么支持泛型Generics
下一篇: C# Event浅析
CSharpIsDog
博客等级 码龄5年 0粉丝 15原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值