使用C#中的通用列表和接口进行类型转换 - 寻找一个优雅的解决方案

Ste*_*don 1 c# generics type-conversion

以下面的例子(纯粹为了证明这一点而创建).我想要做的是将系统的一部分与另一部分隔离,并且只希望在内部对整个对象方法进行内部处理时从程序集外部公开特定的功能子集.

此代码编译,但我在运行时收到无效的强制转换异常.感觉这应该工作但不幸的是它没有.

任何人都可以提出一个优雅的解决方案吗?

更新:基于评论我已经改变了这个例子以更好地展示这个问题,我现在也在样本中展示了对我有用的解决方案......

    using System.Collections.Generic;

    namespace Test
    {
        public class PeopleManager
        {
            List<Person> people = new List<Person>();

            public PeopleManager()
            {
            }

            public void CreatePeople()
            {               
                people.Add(new Person("Joe", "111 aaa st"));
                people.Add(new Person("Bob", "111 bbb st"));
                people.Add(new Person("Fred", "111 ccc st"));
                people.Add(new Person("Mark", "111 ddd st"));                
            }

            public IList<IName> GetNames()
            {
                /* ERROR
                 * Cannot convert type 'System.Collections.Generic.List<Test.Person>' 
                 * to 'System.Collections.Generic.List<Test.IName>' c:\notes\ConsoleApplication1\Program.cs
                 */

                return (List<IName>) people; // <-- Error at this line

                // Answered my own question, do the following

                return people.ConvertAll(item => (IName)item);
            }
        }

        public interface IName
        {
            string Name { get; set; }
        }

        internal class Person : IName
        {
            public Person(string name, string address)
            {
                this.Name = name;
                this.Address = address;
            }

            public string Name
            {
                get;
                set;
            }

            public string Address
            {
                get;
                set;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Eli*_*sha 7

IList<IName> restricted = people.Cast<IName>().ToList(); 
Run Code Online (Sandbox Code Playgroud)