与C-Sharp交互 [英] interface with C-Sharp

查看:99
本文介绍了与C-Sharp交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接口是值类型还是引用类型?

请帮助
我完全感到困惑.


thanq.

Interface is value type or reference type?

please help
i am totally confused.


thanq.

推荐答案

我会添加Collin和Mehdi的基本正确答案:

另一个问题是:我们声明接口类型的变量,它是值类型引用类型吗?
确实是一个有趣的问题.从某种意义上讲,它始终是引用类型,因为这是对某个对象的引用.但!对于变量本身,只有其编译时类型是已知的,如果您知道的话,可以将其称为对某事的引用".当将此变量分配给某个对象时,该对象可以是引用(如果实现类型为类)或值类型(如果实现类型为struct).但是,在struct的情况下,对象总是以引用类型装箱,因为它通过接口类型的变量出现.

从某种意义上说,这是一个非常微妙的问题.

—SA
I would add to the basically correct answer by Collin and Mehdi:

Another question is: we declare a variable of interface type, is it of value type reference type?
Interesting question, really. In certain sense, it is always of reference type, because this is a reference to some object. But! For a variable itself only its compile-time type is known, call it "reference to something" if you well. When this variable is assigned to some object, the object could be either reference (in case if implementing type is a class) or value type (in case if implementing type is struct). In case of struct, however, the object is always boxed in a reference type as it appears through the variable of interface type.

A really delicate issue, in a way.

—SA


接口既不是接口,但实现类型可以是

例如

An interface is neither but the implementing type can be either

e.g.

public interface ITest
{
    void DoSomething();
}

public class TestClass : ITest
{
    public void DoSomething()
    {
        
    }
}

public struct TestStruct : ITest
{
    public void DoSomething()
    {
        
    }
}



参见 MSDN [



see MSDN[^] for more details


都没有.接口是合同.

它可以用于引用或值类型.

例如,

Neither. Interface is a contract.

It can be used on either ref or value types.

For example,

public struct CustomIntCollectionValueType : ICollection<int>
{
  //Implementation here
}
</int>







or

public class CustomIntCollectionRefType : ICollection<int>
{
  //Implementation
}
</int>



在这种情况下,我使用的是系统提供的界面.可以创建自己的接口并将其实现为值类型(结构)或引用类型(类).



In this case I am using a system provided interface. One can create their own interface and implement it upon a value type (struct) or ref type (class).


这篇关于与C-Sharp交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆