ICollection<T> where T implements an interface
Is there any way to d开发者_运维百科o something like this?
public interface ISomething
{
}
public class SomethingThatImplementsISomething: ISomething
{
}
public class SomethingElse
{
public ICollection<ISomething> PropertyName{ get; set; }
}
I've tried it out, and it keeps failing. Any ideas?
ICollection<Models.Awardable>
can not be converted to ICollection<IAwardable>
.
What would happen if someone tried to add an IAwardable
to the collection that wasn't a Models.Awardable
?
Just instantiate a collection of IAwardable
and add instances of Models.Awardable
to it.
Make sure you have using System.Collections.Generic
rather than just using System.Collections
at the top of your compilation unit.
Edited to add:
Actually, this probably has to do with the fact that version of C# prior to 4.0 do not allow for covariance or contravariance for generics. In older versions, a generic field must be defined to use an exact data type, to avoid invalid reference type assignments.
Edited again:
Now that I see the actual error message that you are getting, the problem is not in the definition of the field, but in its use. You need to put an explicit cast in the assignment.
The auto-property
public ICollection<ISomething> PropertyName{ get; set; }
tries to create a backing-field of type ICollection<>
, which will fail. Try something like:
public List<ISomething> PropertyName{ get; set; }
It sounds like what you're trying to do is this:
ICollection<SomethingThatImplementsISomething> collection = new List<SomethingThatImplementsISomething>();
somethingElse.PropertyName = collection;
If that's the case, then this is a generic variance issue. ICollection is not covariant in its element type. (Because it it were, you could now go somethingElse.PropertyName.Add(somethingDifferentThatsAlsoAnISomething);
-- and you'd have added a SomethingDifferentThatsAlsoAnISomething to a list of SomethingThatImplementsISomething, which breaks type safety.)
You need to instantiate a collection of ISomethings:
ICollection<ISomething> collection = new List<ISomething>();
somethingElse.PropertyName = collection;
You can then add SomethingThatImplementsISomething objects to your heart's content:
somethingElse.PropertyName.Add(new SomethingThatImplementsISomething());
精彩评论