Interface

The security type prevents unwanted casting at compile time. How can you achieve the same compile-time security for inherited interfaces?

public interface IBase { }
public interface IFoo : IBase { }
public interface IBar { }


public class Base { }
public class Foo : Base { }
public class Bar { }

public class Test
{
    public void TestInterface()
    {
        IBase item = null;

        IFoo foo = item as IFoo;

        // How to get an error?
        IBar bar = item as IBar;
    }

    public void TestClass()
    {
        Base item = null;

        Foo foo = item as Foo;

        // Error since Bar is not derived from Base
        Bar bar = item as Bar;
    }
}
+4
source share
5 answers

You cannot and should not, because it may not be a mistake. Consider an additional class:

class BarBase : IBase, IBar
{
}

Now:

IBase item = new BarBase();
IBar bar = item as IBar;

This will leave baras a non-zero reference - so why do you want this to be a compile-time error? Note that the compiler should not / should not take note:

  • How did you actually initialize item
  • Regardless of whether there are any classes that implement IBaseandIBar

, . :

public sealed class Sealed {}
public interface IFoo {}

Sealed x = null;
IFoo foo = x as IFoo; // Error

Sealed, IFoo, Sealed, ... .

+2

. , , IBase IFoo, IBar. , .

, item ?

public class BarAndFoo : IBar, IFoo { }
+1

# , , , Base, Bar.

. , , , IBase, , IBar. .

public class BarFoo : IBar, IFoo { }

IBase item = new BarFoo();
IFoo foo = item as IFoo;
IBar bar = item as IBar;
+1

, :

IFoo foo = null;
IBar bar = foo; // Invalid cast at compile-time

as, , , , , , null.

, " " , :

  IFoo foo = new Foo();
  IBar bar = foo as IBar;
  Contract.Assert(bar != null);

... :

Code contracts include classes for marking your code, a static analyzer for analyzing compilation time, and a runtime analyzer. classes for code contracts can be found in System.Diagnostics.Contracts namespace.

+1
source

Keep in mind that an object itemcan be a class that implements both interfaces ( IBaseand IBar), therefore a class of excellent qualities.

class MyImplementation : IBase, IFoo, IBar {
}

IBase x = new MyImplementation();
IBar bar = x as IBar; // valid
0
source

Source: https://habr.com/ru/post/1620298/


All Articles