开发者

Inherited .Net Class ToString Not Overriding

开发者 https://www.devze.com 2023-01-20 13:45 出处:网络
I have created an inherited class \"StorageMedium\" from a base I called \"DataTypes\". StorageMedium has two properties, Name() and Capacity().

I have created an inherited class "StorageMedium" from a base I called "DataTypes". StorageMedium has two properties, Name() and Capacity().

In the DataTypes object, which all other objects in the class library have been inherited from, I have suppressed the Equals, ReferenceEquals, GetHashCode, ToString and GetType functions so these functions are not browsable in the Visual Studio editor.

The purpose is due to the fact the class library will be eventually used by users are not "programmers", and I want to hide any unecessary code or functions they might come across.

I have a second Class that "creates" the instances of the StorageMedium:

    Shared ReadOnly Property DVD() As StorageMedium
        Get
            Return New StorageMedium(NewMedium.DVD)
        End Get
    End Property

    Shared ReadOnly Property CD() As StorageMedium
        Get
            Return New StorageMedium(NewMedium.CD)
        End Get
    End Property

On my webpage, I want to call the creation class and create instance of the StorageMedium and display the name and capacity as a string with the name and capacity

  Response.Write(StorageMedium.Utils.DVD)
  DVD: 4.7Gb

However, when I use the Response.Write method it displays the full class name

  Response.Writ开发者_如何学编程e(StorageMedium.Utils.DVD)
  LC.Utils.Convert.Computer.DataType.StorageMedium

It's fair to assume this is probably caused by the suppression of the basic Object functions, however, is there a way to "rehook-up" or recreate a default function to utilitise the ToString functionality without creating a property like "ToOutput" to display the object as required?

Thanks.


You could try this:

public class StorageMedium {
    // Other code
    public static implicit operator String(StorageMedium instance) {
        return "StorageMedium"; // Or whatever string you prefer
    }
}

Although overriding ToString() is obviously preferred.

0

精彩评论

暂无评论...
验证码 换一张
取 消