加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

指定接口只能通过引用类型C#实现

发布时间:2020-12-15 07:41:57 所属栏目:百科 来源:网络整理
导读:如果我在C#中声明一个接口,有什么方法可以显式声明实现该接口的任何类型都是引用类型? 我想这样做的原因是,无论我在哪里使用接口作为类型参数,我都不必指定实现类型也必须是引用类型. 我想要完成的例子: public interface IInterface{ void A(); int B { g
如果我在C#中声明一个接口,有什么方法可以显式声明实现该接口的任何类型都是引用类型?

我想这样做的原因是,无论我在哪里使用接口作为类型参数,我都不必指定实现类型也必须是引用类型.

我想要完成的例子:

public interface IInterface
{
    void A();
    int B { get; }
}

public class UsingType<T> where T : IInterface
{
    public void DoSomething(T input)
    {
         SomeClass.AnotherRoutine(input);
    }
}

public class SomeClass
{
    public static void AnotherRoutine<T>(T input)
        where T : class
    {
        // Do whatever...
    }
}

由于SomeClass.AnotherRoutine()的参数需要是一个引用类型,我将在这里得到一个编译器错误,我调用该方法,建议我强制T作为引用类型(其中T:IInterface,声明中的类) of UsingType).有什么方法可以在接口级别强制执行此操作吗?

public interface IInterface : class

不起作用(显然)但也许还有另一种方法来完成同样的事情?

解决方法

如果你在一个接口下传递一些东西,那么即使你有一个实现该接口的值类型,如果转换为接口并且行为类似于引用类型(因为它在引用类型中被加框),它将变成盒子.
interface IFoo {
    int Value { get; set; }
}

struct Foo : IFoo {
    public int Value { get; set; }
}

用作值类型时观察效果:

var a = new Foo() { Value = 3 };
var b = a; // copies value
b.Value = 4;
Console.WriteLine( "a has {0}",a.Value ); //output: a has 3
Console.WriteLine( "b has {0}",b.Value ); //output: b has 4

现在看看当你把它投射到界面时会发生什么:

var a = new Foo() { Value = 3 } as IFoo; //boxed
var b = a; // copies reference
b.Value = 4;
Console.WriteLine( "a has {0}",a.Value ); //output: a has 4
Console.WriteLine( "b has {0}",b.Value ); //output: b has 4

因此,结构或类是否实现接口并不重要.如果转换为接口然后在接口下传递,那么它将表现为引用类型.

编辑:那么如果这些是您的要求……

For contract X:

  1. Throw a compile error if a struct implements/inherits X.
  2. X may not be an abstract class.

那么,你只是被卡住了,因为那些相互矛盾.

>如果struct实现/继承契约,那么获取编译错误的唯一方法是它是否为抽象类.
>由于您无法使用抽象类来保持继承选项的打开,因此必须使用接口.
>强制执行结构无法实现接口的规则的唯一方法是在运行时.

使用T:class的约束,IFoo甚至不会一直工作.如果我有这个方法(基于相同的Foo和IFoo):

static void DoSomething<T>(T foo) where T: class,IFoo {
    foo.Value += 1;
    Console.WriteLine( "foo has {0}",foo.Value );
}

然后在这种情况下会抛出编译错误:

var a = new Foo(){ Value = 3 };
DoSomething(a);

但在这种情况下它会正常工作:

var a = new Foo(){ Value = 3} as IFoo; //boxed
DoSomething(a);

因此,就我而言,使用T:class,IFoo-style约束,然后只要它被装箱,结构就实现了接口可能无关紧要.但是,如果传递一个盒装结构,则取决于检查EF的作用.也许它会起作用.

如果它不起作用,至少通用约束会让你分开,你可以检查foo.GetType().IsValueType(指上面我的DoSomething方法)并抛出ArgumentException来处理盒装结构的情况.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读