《illustrate c# 2008》:

User-Defined Type Conversions

用户定义类型转换
User-defined conversions are discussed in greater detail in Chapter 18, but I will mention them here as well because they are operators.

用户定义类型转换 are discussed in greater detail in Chapter 18。但是我仍然将提到他们,在这里,因为它们是操作符
• You can define both implicit and explicit conversions for your own classes and structs.

可以为自己的类或者结构定义both  implicit and explicit conversions
This allows you to convert an object of your user-defined type to some other type, and vice versa.

这允许你转化一个类型 of 你的用户定义类型 to 另外别的类型,反之亦然。
• C# provides implicit and explicit conversions.

c#提供隐式和显式转化
– With an implicit conversion, the compiler will automatically make the conversion, if necessary, when it is resolving what types to use in a particular context.

通过implicit conversion,编译器能够自动进行转化,如果有必要,当在决定使用什么类型-----在特定的上下文。
– With an explicit conversion, the compiler will only make the conversion when an explicit cast operator is used.

通过显式转化,编译器能够进行转化,但是要符合条件:when an explicit cast operator is used.
The syntax for declaring an implicit conversion is the following. The public and static modifiers are required for all user-defined conversions.

隐式转化的语法如下,public和static修饰符be required ,对所有用户自己定义的类型转换

Required           Target       Source
____↓____________                ↓      ______↓____________
public static implicit operator TargetType ( SourceType Identifier )
{
...
return ObjectOfTargetType;
}

 

 

 

The syntax for the explicit conversion is the same, except that explicit is substituted for implicit.

显式转化的语法相同,除了用explicit 替换掉 implicit
The following code shows an example of declarations for conversion operators that will convert an object of type LimitedInt to type int, and vice versa.

下面的代码shows 声明转换操作符的一个例子。这个例子用来把LimitedInt类型的对象转换成int类型的对象,反之亦然。

class LimitedInt

                                           Target   Source
{                                            ↓           ↓
    public static implicit operator int (LimitedInt li)
    {
        return li.TheValue;
    }

                                Target   Source
                                ↓          ↓
    public static implicit operator LimitedInt (int x)
    {
        LimitedInt li = new LimitedInt();
        li.TheValue = x;
        return li;
    }
    private int _TheValue = 0;
    public int TheValue{ ... }
}

 

posted on 2010-08-22 18:50  菜刀大侠  阅读(389)  评论(0编辑  收藏  举报