开发者

Why does the check for an interface fail?

开发者 https://www.devze.com 2022-12-30 13:51 出处:网络
I have a class that implements an interface. In another area of the code I check if that class instance contains that interface, but it doesn\'t work. The check to see if the class contains the interf

I have a class that implements an interface. In another area of the code I check if that class instance contains that interface, but it doesn't work. The check to see if the class contains the interface always fails (false) when it should be true.

Below is a simple representation of what I am trying to accomplish.

Example

  pu开发者_开发问答blic interface IModel
    {
        bool validate();
    }


  public class SomeModel : IModel
    {
        public SomeModel
        {
        }

        public bool Validate()
        {
            return true;
        }        
    }



    // Dummy method
    public void Run()
    {
        SomeModel model = new SomeModel();

        if (model is IModel)
        {
           string message = "It worked";
        }
        else
        {
            string message = "It failed";
        }
    }


Did you make sure you tested against the correct interface? By that I mean, is your "is" test using the correct version of IModel? IModel doesn't strike me as a unique type name, so you may have imported an incorrect namespace.

Try explicitly qualifying your check.

I.e.

   if (model is MyNamespace.IModel) ...


One very common error here is to declare the interface in two different assemblies, for example by including the same .cs file in two different dlls. Since types are defined by their assembly, this gives two conflicting interfaces, which happen to have the same name.

The same scenario is also common (with different namespaces), for example when importing web-services; the proxy/generated type is different to the originating type.


Validate is written lower case in the interface and upper case in the class. Your example shouldn't even compile, as it is an compiler error.

0

精彩评论

暂无评论...
验证码 换一张
取 消