通过接口访问不同的对象属性? C#

Access to different object properties through an interface? C#

我正在用 C# 上的工厂模式编写一个 dll。工厂收到一个枚举和 return 一个接口。根据接收到的枚举,它创建不同的对象并 return 它封装在接口中。工厂内部的任何 class 都实现了该接口,并且其访问修饰符是内部的,除了自己的接口 public。

问题是当我从主项目调用 dll 时。在工厂内创建的每个对象都有不同的属性,这不是为什么我不能从 main 访问或修改这些属性。有帮助吗?

这是主函数的工厂调用。

IConfigurator config = ConfigFactory.Instance.CreateConfigurator(Model.First);

工厂是这样工作的(在 dll 内部):

public IConfigurator CreateConfigurator(Model model)
    {
        switch (model)
        {
            case Model.First:
                return (First)new First(model);

            case Model.Second:
                return (Second)new Second(model);

            case Model.Third:
                return (Third)new Third(model);

        }

    }

第一、第二和第三具有不同的属性,我无法从收到的接口对象中修改它

谢谢。

该方法只能有一个 return 类型。 不是通过枚举选择结果,而是为每个项目创建不同的工厂方法/工厂class。

样本:

// instead of this
public enum FactoryEnum {
   VariantA,
   VariantB,
   VariantC
}
object Create(FactoryEnum item);

// do this
IMyInterfaceA CreateA();
IMyInterfaceB CreateB();
IMyInterfaceC CreateC();

简短的回答是您要返回一个接口,因此只有作为接口一部分的属性才可用,直到您将对象转换为其具体类型。

例如:

public class A : INameable
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class B : INameable
{
   public string Name { get; set; }
   public string Description { get; set; }
}

public Interface INameable
{
   string Name { get; set; }
}

public Enum Selector
{
    A,
    B
}

所以如果我使用如下方法

public INameable GetINameable(Selector selector)
{
   if (selector.Equals(Selctor.A))
       return new A { Name = "Name A", Age = 10 };
   if (selector.Equals(Selector.B))
       return new B { Name = "Name B", Description = "New Instance of B"};
}

我将返回一个 INameable 的实例,并且只能访问接口中定义的 Name 属性。

但是,如果我需要访问其他属性,则需要将返回的对象转换为其具体类型,如下所示:

// This will be an instance of INameable
var obj = GetINameable(Selector.A);

// Now cast as an instance of A
var castObj = obj as A;

// We can now access the Age property
var age = castObj.Age;