【问题标题】:Pass an object to a method with Interface return type将对象传递给具有接口返回类型的方法
【发布时间】:2014-05-28 01:07:01
【问题描述】:

如何将对象传递给具有接口返回类型的方法?这可能吗?

例如:

public enum Objects{obj1, obj2, obj3 }

public class SomeClass1
{
    public string property1;
    public string property2;
    public string property3;    
}

public class SomeClass2
{
    private IList<IInterface> interface;
    public SomeClass2(IList<IInterface> interface)
    {
        this.interface = interface;
    }

    public Iinterface GetEnumObjects(SomeClass1 someClass1)
    {
        return interface.Where(o => o.isItTrue(someClass1)).FirstOrDefault();
    }    
}

public interface IInterface()
{
    Objects objects {get;}    
    public bool isItTrue(SomeClass1 someClass1);    
}

public static void main(string[] args)
{
    SomeClass1 someObject1 = new SomeClass 
    {
        property1 = "prop1"
        property1 = "prop2"
        property1 = "prop3"
    };

    // How can I pass an object to a method with interface return type?
    PassThisObject(someOtherObject );    
}

【问题讨论】:

  • @Leo 我应该如何在 Main 中初始化 SomeClass2() 以将对象传递给 GetEnumObjects() 方法?

标签: c# oop polymorphism


【解决方案1】:
public bool isItTrue; 

应该是。

public bool isItTrue(SomeClass1 someClass1)

【讨论】:

  • 正确!匆忙输入了这个东西
  • 我应该如何在 Main 中初始化 SomeClass2() 以将对象传递给 GetEnumObjects 方法?
【解决方案2】:

不知何故,你的例子不是很清楚。如果您传递的类型的对象实现了该接口,那么请确保您可以。示例...

//Method Definition
public Iinterface PassThisObject(Someclasssomeotherobject someOtherObject )
{
   //Your code here
}


//Class definition
class Someclasssomeotherobject : Iinterface
{
 //class members here
}

//You can call the method like

Someclasssomeotherobject someOtherObject = new Someclasssomeotherobject();

PassThisObject(someOtherObject );

编辑:

对您的代码进行如下更改

//have your class implements the interface
public class SomeClass1 : IInterface
{
    public string property1;
    public string property2;
    public string property3;    
}


public static void main(string[] args)
{
    SomeClass1 someObject1 = new SomeClass 
    {
        property1 = "prop1"
        property1 = "prop2"
        property1 = "prop3"
    };
        //Create a list of IInterface
       List<IInterface> listofinterface  = new List<IInterface>();

       //Instanciate someclass2 passing the interface list created in earlier step
       SomeClass2 cls2 = new SomeClass2(listofinterface);

       //call your GetEnumObjects method passing the someclass1 object
       cls2.GetEnumObjects(someObject1);  
}

【讨论】:

  • 我收到一个错误:非静态字段、方法或属性“ConsoleApplication1.SomeClass2.GetEnumObjects(ConsoleApplication1.SomeClass1)”需要对象引用
  • 我应该如何在 Main 中初始化 SomeClass2() 以将对象传递给 GetEnumObjects 方法?
  • @user793468,请参阅编辑后的答案。确保澄清您帖子中的所有内容并仅显示相关代码以避免混淆,并提高您快速正确获得答案的机会。
  • 我认为我们不能创建任何接口的实例
  • @user793468,是的,没看到。现在应该好了。再试一次。 List 实现 IList
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多