将对象传递给具有Interface返回类型的方法

本文关键字:Interface 返回类型 方法 对象 | 更新日期: 2023-09-27 18:05:23

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

例如

:

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 );    
}

将对象传递给具有Interface返回类型的方法

public bool isItTrue; 

public bool isItTrue(SomeClass1 someClass1)

不知怎么的,你的例子不是很清楚。如果你要传递的类型对象实现了那个接口,那么你当然可以。例子…

//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);  
}