I am a newbie to C#. Could you please tell me how to pass an interface as a parameter to a method?
i.e. I want to access the interface members(property) and assign the values to it and send that interface as a parameter to another method.Say for example if I have an interface as IApple which has members as property int i and int j I want to assign values to i and j and send the whole interface as a parameter say like this
Method(IApple var);
开发者_JAVA技巧Is it possible? Sorry if am poor at basics please help me out. thanks in advance
Sure this is possible
public interface IApple
{
int I {get;set;}
int J {get;set;}
}
public class GrannySmith :IApple
{
public int I {get;set;}
public int J {get;set;}
}
//then a method
public void DoSomething(IApple apple)
{
int i = apple.I;
//etc...
}
//and an example usage
IApple apple = new GrannySmith();
DoSomething(apple);
Say you have the following classes:
public interface IApple{
int I {get; set;}
int J {get; set;}
}
public class GrannySmith : IApple{
public GrannySmith()
{
this.I = 10;
this.J = 6;
}
int I {get; set;}
int J {get; set;}
}
public class PinkLady : IApple{
public PinkLady()
{
this.I = 42;
this.J = 1;
}
int I {get; set;}
int J {get; set;}
}
public class FruitUtils{
public int CalculateAppleness(IApple apple)
{
return apple.J * apple.I;
}
}
now somewhere in your program you could write:
var apple = new GrannySmith();
var result = new FruitUtils().CalculateAppleness(apple);
var apple2 = new PinkLady();
var result2 = new FruitUtils().CalculateAppleness(apple2);
Console.WriteLine(result); //Produces 60
Console.WriteLine(result2); //Produces 42
精彩评论