Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

oop - How do i convert a List<Interface> to List<Class> in c#

I have an interface defined as

public interface IReaderInfo
{
    string Displayname {get;}
}

and a class that implements that interface

public class ReaderInfo : IReaderInfo
{
    string DisplayName {get;}
}

I then created a function which return List

public List<ReaderInfo> GetReaders
{
     var readers = new List<ReaderInfo>();
     var Ireaders = someobject.Getreaders();// Returns the list of IReaderInfo.
     // Now i would like cast Ireaders as readers and return.
}

How do i cast it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have to create a new list with casted items:

var readers = Ireaders.Cast<ReaderInfo>().ToList();

Or, if there is a possibility to have incompatible IReaderInfo entries and you only want the actual ReaderInfo objects in the result:

var readers = Ireaders.OfType<ReaderInfo>().ToList();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...