What is the difference between casting and coercing?

后端 未结 7 1771
名媛妹妹
名媛妹妹 2020-12-02 06:45

I\'ve seen both terms be used almost interchangeably in various online explanations, and most text books I\'ve consulted are also not entirely clear about the distinction.

7条回答
  •  庸人自扰
    2020-12-02 06:58

    Casting is the process by which you treat an object type as another type, Coercing is converting one object to another.

    Note that in the former process there is no conversion involved, you have a type that you would like to treat as another, say for example, you have 3 different objects that inherit from a base type, and you have a method that will take that base type, at any point, if you know the specific child type, you can CAST it to what it is and use all the specific methods and properties of that object and that will not create a new instance of the object.

    On the other hand, coercing implies the creation of a new object in memory of the new type and then the original type would be copied over to the new one, leaving both objects in memory (until the Garbage Collectors takes either away, or both).

    As an example consider the following code:

    class baseClass {}
    class childClass : baseClass {}
    class otherClass {}
    
    public void doSomethingWithBase(baseClass item) {}
    
    public void mainMethod()
    {
        var obj1 = new baseClass();
        var obj2 = new childClass();
        var obj3 = new otherClass();
    
        doSomethingWithBase(obj1); //not a problem, obj1 is already of type baseClass
        doSomethingWithBase(obj2); //not a problem, obj2 is implicitly casted to baseClass
        doSomethingWithBase(obj3); //won't compile without additional code
    }
    
    • obj1 is passed without any casting or coercing (conversion) because it's already of the same type baseClass
    • obj2 is implicitly casted to base, meaning there's no creation of a new object because obj2 can already be baseClass
    • obj3 needs to be converted somehow to base, you'll need to provide your own method to convert from otherClass to baseClass, which will involve creating a new object of type baseClass and filling it by copying the data from obj3.

    A good example is the Convert C# class where it provides custom code to convert among different types.

提交回复
热议问题