سؤال

Consider the following scenario:

Public Class Condition(Of T)

    '...

End Class

Now, I create several instances of this class with various types. I now desire to populate a generic list with these instances. Something like:

Dim Conditions As New List(Of Condition....?)
Conditions.add(new Condition(Of String))
Conditions.add(new Condition(Of Double))
Conditions.add(new Condition(Of CustomClass))

What is the best way to do this? For now I am doing the following:

Public Class Condition(Of T)
    implements ICondition

    '...

End Class

And using it like so:

Dim Conditions As New List(Of ICondition)
Conditions.add(new Condition(Of String))
Conditions.add(new Condition(Of Double))
Conditions.add(new Condition(Of CustomClass))

However, ICondition is just totally empty. Which makes me think there is probably a better or more accepted way to go about things. I could also inherit from an empty base class, would that be better? What is the preferred method of doing this kind of thing?

I understand that so long as the list that contains the generics is of a broader type that I can insert conditions of any type. However I do not want to make it any broader than necessary - I only want to be able to insert objects that are instances of Public Class Condition(Of T), but whose types may vary.

هل كانت مفيدة؟

المحلول

The answer differs, depending upon the version of the .NET Framework that you're using. Look up articles about covariance and contravariance to understand the problem. Here's an example.

.NET 4 and 4.5 support this kind of usage.

Earlier versions of .NET would make you use something like the ICondition interface that you mention.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top