Problem: Cannot call method in class, which is explicitly implemented from interface, through new object
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace practise
{
class Program
{
static void Main(string[] args)
{
ctest ctestoa = new ctest();
ctestoa.printa(); // error, can not call "printa()"
}
}
class ctest : itest
{
public void printa()
{
Console.WriteLine("itest.printa");
}
}
interface itest
{
public void printa();
}
}
Cause: http://msdn.microsoft.com/en-us/library/aa664591%28VS.71%29.aspx
Explicit interface member implementations serve two primary purposes:
- Because explicit interface member implementations are not accessible through class or struct instances, they allow interface implementations to be excluded from the public interface of a class or struct. This is particularly useful when a class or struct implements an internal interface that is of no interest to a consumer of that class or struct.
- Explicit interface member implementations allow disambiguation of interface members with the same signature. Without explicit interface member implementations it would be impossible for a class or struct to have different implementations of interface members with the same signature and return type, as would it be impossible for a class or struct to have any implementation at all of interface members with the same signature but with different return types.
Solution:
1. not explicitly implement interface in class.
then as we new oject, method can be call. like this
namespace practise
{
class Program
{
static void Main(string[] args)
{
ctest ctestoa = new ctest(); // object is "ctest" type
ctestoa.printa();
}
}
class ctest : itest
{
public void printa()
{
Console.WriteLine("itest.printa");
}
}
interface itest
{
public void printa();
}
}
2. new interface instance, not just class object
namespace practise
{
class Program
{
static void Main(string[] args)
{
itest ctestoa = new ctest();
ctestoa.printa();
}
}
class ctest : itest
{
public void itest.printa()
{
Console.WriteLine("itest.printa");
}
}
interface itest
{
public void printa();
}
}
That's all. Thank you