Tag: implicit cast

当B可以打印到A时,如何将A转换为A类对象?

基本上我想这样做。 aa会导致错误的强制转换exception。 注意:o可以是任何东西。 它可能不是B,它可以是C,D,E,F等。但是只要o是一个可以类型转换为A的类(B就是这样一个类,它就可以使用隐式运算符重载)。 var b = (B)”sz”; var a = (A)b; object o = b; var aa = (A)o;

C#中的隐式数组转换

我有以下类定义了隐式转换运算符: class A { … } class B { private A m_a; public B(A a) { this.m_a = a; } public static implicit operator B(A a) { return new B(a); } } 现在,我可以隐含地将A转换为B. 但为什么我不能隐含地将A []强制转换为B []? static void Main(string[] args) { // compiles A a = new A(); B b = a; // doesn’t compile […]

C#隐式转换“重载”和reflection问题

我有以下代码的问题(编译但崩溃): using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ConsoleApplication1 { public struct MyBoolean { public bool Value { get; set; } //cast string -> MyBoolean public static implicit operator MyBoolean(System.String value) { return new MyBoolean() { Value = (value[0] == ‘J’) }; } //cast bool -> MyBoolean public static implicit operator […]

c#编译器是否会执行多个隐式转换以从一种类型转换到另一种类型?

假设您有自己的类如下: public sealed class StringToInt { private string _myString; private StringToInt(string value) { _myString = value; } public static implicit operator int(StringToInt obj) { return Convert.ToInt32(obj._myString); } public static implicit operator string(StringToInt obj) { return obj._myString; } public static implicit operator StringToInt(string obj) { return new StringToInt(obj); } public static implicit operator StringToInt(int obj) { […]

隐含版本的IsAssignableFrom?

在我的代码中使用我写的reflection if (f.FieldType.IsAssignableFrom(“”.GetType())) 我有一个隐式转换为字符串的类。 但是上面的if语句并没有抓住它。 我如何使用隐式字符串转换使reflection/上面的if语句捕获字符串和类? 而不是具体的字符串和我知道的每个类?

当派生类型为1作为参数传递时,双向隐式可转换类型的重载之间的模糊调用

(试图找到一个总结问题的标题可能是一项非常艰巨的任务!) 我有以下类与一些重载方法,产生一个调用歧义编译器错误: public class MyClass { public static void OverloadedMethod(MyClass l) { } public static void OverloadedMethod(MyCastableClass l) { } //Try commenting this out separately from the next implicit operator. //Comment out the resulting offending casts in Test() as well. public static implicit operator MyCastableClass(MyClass l) { return new MyCastableClass(); } //Try commenting this out […]

隐式转换Null-Coalescing运算符结果

通过以下对C#中的空合并运算符(??)的理解。 int? input = -10; int result = input ?? 10;//Case – I //is same as: int result = input == null? input : 10; // Case – II 而根据定义和用法,案例I和案例II是相同的。 令人惊讶的是,在Case-I编译器能够隐式转换int? to case而在Case-II中它显示错误:’错误1无法隐式转换类型’int?’ ‘int’“ 关于null-coalescing运算符,我错过了什么? 谢谢你的关注。

在三元语句中没有隐式int – > short转换

short s; s = (EitherTrueOrFalse()) ? 0 : 1; 这失败了: 错误CS0266:无法将类型’int’隐式转换为’short’。 存在显式转换(您是否错过了演员?) 任何人都可以解释为什么会这样吗? 我唯一能想到的是编译器没有查看第二个值而且不知道两者之间的范围,在我编写类似的情况下 short s; s = (EitherTrueOrFalse()) ? 0 : 65000; 正确? 唯一的解决方案是丑陋的演员? 此外,似乎C#没有短类型的类型后缀。 这是一个非常严重的监督IMO。 否则,那将是一个解决方案……