在通用C#类中链接隐式运算符 [英] Chaining implicit operators in generic c# classes

查看:100
本文介绍了在通用C#类中链接隐式运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于以下通用c#类,我想将T转换为K:

For the following generic c# class, I'd like to convert T to K:

public abstract class ValueType<T,K> : IValueType<T> where K : ValueType<T,K>,new()
{     
    public abstract T Value { get; set; }     

    public static implicit operator ValueType<T,K>(T val) 
    {         
        K k = new K();
        k.Value = val;
        return k;    
    }
}

如果我要实现直接运算符implicit operator K(T val),则将导致编译时错误(CS0556).

If I were to implement a direct operator implicit operator K(T val) it would result in a compile-time error (CS0556).

我认为我可以尝试链接隐式运算符:

I thought I could try chaining implicit operators:

public static implicit operator K(ValueType<T,K> vt){
    return (K)val;
}

,但是下面的示例仍然抱怨无法转换:

but the following example still complains that it can't be converted:

public class Test : ValueType<int, Test>
{
    public override int Value{ get; set; }
}

Test t = 6; //complains it's unable to be converted
Console.WriteLine(t.Value);

如果可能的话,我真的想避免显式投射.

I really want to avoid explicitly casting if possible.

这个问题是我之前提出的另一个SO问题.

This question extends upon another SO question I've previously raised.

推荐答案

实现自己的隐式转换逻辑的规则非常严格,如果您对本规范的6.4.4和10.10.3节非常熟悉,将要做这样特别复杂的事情.

The rules for implementing your own implicit conversion logic are quite strict and you should probably become very familiar with sections 6.4.4 and 10.10.3 of the specification if you're going to do particularly complicated ones like this.

简而言之,您应该了解一些关键规则:

Briefly, a few key rules you should know are:

  • 定义转换所用的类型必须出现在用户定义的转换的至"或从"部分中.您不能创建定义从E到F的转换的C类; C必须在某个地方.
  • 永远不可能用您自己的一个替换内置的隐式转换;例如,当您从C转换为对象时,就不会发生特殊行为.
  • 用户定义的隐式转换将与最多两个内置的隐式转换链接",但不能与任何其他用户定义的转换链接".因此,例如,如果您具有从C到D的用户定义的隐式转换,以及从D到IFoo的内置隐式转换,那么您将获得从C到IFoo的隐式转换.但是,如果D具有用户定义的到E的隐式转换,那么您就不会免费获得从C到E的隐式转换.

这篇关于在通用C#类中链接隐式运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆