简体   繁体   中英

C#: Upper cast - List<Interface> to List<Class> - cast obejct of internal class

I have an interface defined as

public interface INamedReader
{
     string DisplayInfoLine { get; }
     string DisplayName { get; }
}

and a class which implements that interface but it is an internal class

internal class NamedReader : INamedReader, INotifyPropertyChanged
    {
        public NamedReader();

        public string DisplayInfoLine { get; set; }
        public string DisplayName { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string ToString();
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "");
        protected virtual bool Set<TField>(ref TField field, TField value, [CallerMemberName] string propertyName = "");
    }

and a class which implements the above NamedReader class

internal class NamedReaderDevice : NamedReader
{
    public NamedReaderDevice();

    public string Id { get; set; }
}

and now i defined class which implements INamedReader

public class ReaderDetails: INamedReader
{
     public string DisplayInfoLine { get; }

     public string DisplayName { get; }
}

I then created a function which return List.

public List<ReaderDetails> GetReaders
{
     var readers = new List<ReaderDetails>();
     var Ireaders = someobject.Getreaders();// Returns the list of NameReaderDevice (which is an internal class).
     // Now i would like cast Ireaders as readers and return.
}

can someone please help me out in this, that would be great.

You are basically trying to convert one class into an entirely different one, like in this picture, trying to convert Class2 to Class3 :

在此输入图像描述

In this scenario, even if they share an interface, you cannot cast between one and the other.

You have a few options:

  1. use a method (extension or otherwise) to convert between classes, using Reflection or serialization (not very efficient)
  2. use a conversion operator (more details here )
  3. return an interface instead of an explicitly implemented class in your Getreaders() method and then use an interface in your application instead of an explicitly implemented class;

In case of (3) if you need or want to further decouple your class implementation, then you may use dependency injection for it (eg. SimpleInjector , accessible through nuget). In that scenario you can for example create objects of said interface in code that does not have acces to the internal class implementing it,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM