相关疑难解决方法(0)

如何确定C#中是否存在隐式转换?

我有两种类型,T和U,我想知道是否从T到U定义了隐式强制转换运算符.

我知道IsAssignableFrom的存在,这不是我正在寻找的,因为它不涉及隐式转换.

一些谷歌搜索引导我到这个解决方案,但在作者自己的话这是丑陋的代码(它试图隐式转换,如果有异常则返回false,否则为true)

似乎测试是否存在具有正确签名的op_Implicit方法将不适用于基本类型.

是否有更简洁的方法来确定隐式转换运算符的存在?

.net c# reflection casting implicit-conversion

22
推荐指数
3
解决办法
2212
查看次数

如何从反射执行显式操作转换?

我想使用反射,并使用反射进行隐式或显式转换.

鉴于我已经用这种方式定义了Foo

public class Foo
{
    public static explicit operator decimal(Foo foo)
    {
        return foo.Value;
    }

    public static explicit operator Foo(decimal number)
    {
        return new Foo(number);
    }

    public Foo() { }

    public Foo(decimal number)
    {
        Value = number;
    }

    public decimal Value { get; set; }

    public override string ToString()
    {
        return Value.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时

decimal someNumber = 42.42m;

var test = (Foo)someNumber;

Console.WriteLine(test);        // Writes 42.42 No problems
Run Code Online (Sandbox Code Playgroud)

当我尝试使用Foo定义一个类作为成员类型并使用反射来设置它时.我得到以下例外.

Error     : Object of type 'System.Decimal' cannot be converted …
Run Code Online (Sandbox Code Playgroud)

c# operators implicit-conversion explicit-conversion

11
推荐指数
2
解决办法
6238
查看次数

C#隐式转换"重载"和反射问题

我遇到以下代码的问题(编译但崩溃):

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 MyBoolean(bool value)
        {
            return new MyBoolean() { Value = value };
        }

        //cast MyBoolean -> bool
        public static implicit operator bool(MyBoolean value)
        {
            return value.Value; …
Run Code Online (Sandbox Code Playgroud)

c# reflection implicit-cast

3
推荐指数
1
解决办法
1357
查看次数