开发者

Casting woes with generic class which needs to know the specific value of T (out of a possible 30 different types) - is this scalable?

开发者 https://www.devze.com 2022-12-09 15:38 出处:网络
I am working with a 3rd party web testing API which has a Src property for image. What I need to do is say:

I am working with a 3rd party web testing API which has a Src property for image.

What I need to do is say:

if (t is HtmlImage) { // Do cast here. } // t is a variable of type T (my generic).

However, my cast does not work. The cast is as follows:

Controls.HtmlImage img = (Controls.HtmlImage)t; 

This gives an error stating that I cannot convert 开发者_如何转开发Type 'T' to HtmlImage. BUT type T is the base class for all controls, including HtmlImage.

The problem I am trying to solve is I have a utility method to loop through a site's pages, but if I am passing Html Image as the value of T, I get the src property as I need the paths (to identify which images have no alt tags, and the src property can never be null). If T is of another type, I will get another property as an identifier. I am testing if images have alt tags, links have meaningful descriptions, etc. For a possible type total of about 30, is this scalable? Because I will be saying if T is Button, else, etc etc for quite a lot of types (could use table driven method).

HtmlImage inherits from:

public class HtmlImage : ArtOfTest.WebAii.Controls.HtmlControls.HtmlControl

T is of type HtmlControl

Thanks


You can't cast because the compiler doesn't necessarily know what a cast would mean. Casts can be used for boxing, unboxing, user-defined conversions or straight reference type conversions. The latter is what you're most interested in.

On the other hand, "as" works because it's always just a reference type conversion (unless you use it with a nullable type as the right hand operand).

In fact, you can use a cast, but only if you go through object first (which would always be either a boxing conversion or a reference conversion, but never a user-defined conversion):

HtmlImage hi = (HtmlImage) (object) hi;

I'd use as though, personally...


To answer my own question, this doesn't through a design time error:

Controls.HtmlImage img = t as Controls.HtmlImage;

But why doesn't the () operator work normally?

The other question left is the scalability of this sort of approach. Is there another, better, way?


I am not sure to understand. Try to add where T : HtmlImage in your methode definition


Controls.HtmlImage img = t as Controls.HtmlImage;

But why doesn't the () operator work normally?

When using the "as" keyword, a cast is invoked but when this doesn't succeed, like when img == null then it will return null. A cast through () will generate a exception when the cast didn't succeed.

0

精彩评论

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