Cannot call method in class, which is explicitly implemented from interface, through new object

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值