In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how to achieve custom implicit conversion and explicit conversion in C#. It has a certain reference value, and interested friends can refer to it. I hope you will gain a lot after reading this article. Let's take a look at it.
Basic knowledge
There are two types of type conversions: implicit and explicit. However, whether it is an implicit or explicit conversion, a new object is generated and returned. Changing the properties of the new object will not affect the old object! (except for dynamic objects, details search for dynamic dynamic types.)
A custom implicit / explicit conversion method requires several keywords: implicit (implicit conversion), explicit (explicit conversion), and operator (operator). For more attention, see the following:
Method must be static
Use implicit or explicit
With operator (this is also the c# relation word, you can build multiple operators or provide user-defined transitions in the category or structure declaration)
The return value is the target type to be converted to, but do not declare it on the method, the method name is the target type. Note: the return value is not necessarily the type of this class. This type and other types can be converted to each other, as long as the conversion method is defined.
The parameter is the original type, and the method name is the target type.
The type conversion definition from class A to class B cannot be done in class C (that is, the conversion of two classes cannot be defined in the third class), otherwise an error will be reported: the user-defined conversion must be converted to or from a closed type. Specifically, the following user-defined conversions must be converted to closed types, or from closed types
Cannot be modified by virtual/override (cannot "override" operators because they are static. ) Overriding implicit operators in C#
Sample code / / = define types and methods = class Robot {public int Id {get; set;} public string Name {get; set;} public Robot (int id, string name) {Id = id; Name = name;} # region other types-> this class / / implicit conversion public static implicit operator Robot (string name) {return new Robot (101, name) } / / explicit conversion public static explicit operator Robot (int id) {return new Robot (id, "miku");} # endregion # region this class-> other types / implicit conversion public static implicit operator string (Robot robot) {return robot.Name;} / / explicit conversion public static explicit operator int (Robot robot) {return robot.Id } # endregion} / / = Test code = # region other types-> this class string gumiStr = "gumi"; Robot gumi001 = gumiStr; / / implicit conversion Console.WriteLine ("implicit conversion: gumi001: {0}", JsonConvert.SerializeObject (gumi001)); int lukaId = 1004 JsonConvert.SerializeObject luka001 = (Robot) lukaId; / / explicit conversion Console.WriteLine ("explicit conversion: luka001: {0}", JsonConvert.SerializeObject (luka001)) # endregion#region other types-> this class Robot miku001 = new Robot (1001, "miku10001"); / / implicit conversion string mikuName = miku001;// explicit conversion int mikuId = (int) miku001;Console.WriteLine ("implicit conversion: miku001 Name: {0}", mikuName); Console.WriteLine ("explicit conversion: miku001 Id: {0}", mikuId); # endregion
The output is as follows:
Implicit conversion: gumi001: {"Id": 101, "Name": "gumi"}
Explicit conversion: luka001: {"Id": 1004, "Name": "miku"}
Implicit conversion: miku001 Name: miku10001
Explicit conversion: miku001 Id: 1001
Practical application problems
[1, [[2,2], [2,2], [2,2], [2,2]
How can such a string be deserialized into an object? (how do you define this class? )
The answer using System;using System.Linq;using System.Collections.Generic;using Newtonsoft.Json;using Newtonsoft.Json.Linq; public class Program {public static void Main () {var json = "[1, [2jue 2], [2jue 2], [2jue 2], [2je 2]; var root = JsonConvert.DeserializeObject (json) Foreach (var ele in root) {if (ele.SingleValue.HasValue) {/ / has a value, and the original data is 1 Console.WriteLine (ele.SingleValue.Value) } else {/ / Raw data is a two-dimensional array Console.WriteLine (string.Join ("", ele.Select (x = > string.Join (",", x);}} Console.WriteLine (JsonConvert.SerializeObject (root)) }} class Root: List {} [JsonConverter (typeof (CConverter))] class Element: List {/ / this attribute, store 1. Later, you can know about the original data by determining whether the attribute has a value or not, public long? SingleValue {get; set;} / / encountered 1 and implicitly converted to this type, where 1 is stored in the SingleValue attribute public static implicit operator Element (long d) {return new Element {SingleValue = d};}} public class CConverter: JsonConverter {public override bool CanConvert (Type objectType) {return (objectType = = typeof (Element)) } public override bool CanRead {get {return false;}} public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {throw new NotImplementedException ();} public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) {var ele = value as Element; var token = ele.SingleValue.HasValue? JToken.FromObject (ele.SingleValue.Value): JToken.FromObject (ele.ToList ()); token.WriteTo (writer);} public override bool CanWrite {get {return true;}} error report
User-defined conversions must be converted to or from closed types
This error has nothing to do with the closed type.
Because of this restriction: the type conversion definition from class A to class B cannot be done in class C (that is, the conversion of two classes cannot be defined in the third class).
So if the target type is the collection class List, we cannot directly define the conversion to it. However, there are two circuitous ways:
Create a class that inherits from the collection class List and defines the transformation to this subclass. The code in the actual application above does this: class Element: List
Create a custom transformation from T1 to T2 and convert it one by one: list.Select (p = > (B) p) .ToList ().
Other applications and designs
When defining a category, you can use these two related words to provide some additional functions if necessary.
However, it is also necessary to check whether the design is reasonable when using it.
For example, whether or not to extract a parent class or interface for use when a category is related, instead of making a bunch of transformations for convenience, leading to difficulties in programming and maintenance.
Pronunciation
Implicit conversion: implicit [implicit pl's implicit t] adj. Unspoken [implicit]; unquestionable, absolute; part of; implied
Explicit conversion: explicit ["k" spl's "t] adj. Clear, clear, outspoken, detailed, unconcealed
Thank you for reading this article carefully. I hope the article "how to realize custom implicit conversion and explicit conversion of C#" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.