C#是否像C ++一样使公共/私有之后的所有内容? [英] C# Make everything following public / private like in C++?

查看:40
本文介绍了C#是否像C ++一样使公共/私有之后的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始学习C#,但是我对C ++有一定的了解.我想知道我会怎么做

I recently started learning C#, but I have some background in C++. I was wondering how I would do something like

class employee
{
    public:
       ....
  ... methods ...
       ....

    private:
       ....
    ... private member variables ....
       ....
}

我尝试在C#中执行此操作,但它不喜欢"public:..."和"private:..."将所有内容公开或私有化.

I tried doing this in C#, but it doesn't like the "public: ..." and "private: ..." to make everything after it either public or private.

此外,我已经看到C#中有此get和set东西,因此您不需要通过创建私有成员变量然后创建函数来返回该变量的方式来做这些事情?

Also, I've seen that theres this get and set thing in C#, so you don't need to do things in the way of making a private member variable, then making a function to return that variable?

当我这样做时,如何在C#中创建子类?在C#中,新类在不同的选项卡中打开,因此我对如何执行此操作感到困惑.

While i'm at it, how does one make subclasses in C#? In C# new classes get opened in different tabs, so I'm confused as to how I would do it.

推荐答案

您无法像在C ++中那样在C#中将块"设为公开或私有,您必须为每个对象添加可见性(和实现)成员.在C ++中,您通常会这样做;

You can't make "blocks" public or private in C# as you would in C++, you'll have to add the visibility (and implementation) to each member. In C++, you'd normally do;

public:
  memberA();
  memberB();
private:
  memberC();

...并在其他地方实现您的成员,而在C#中,您需要这样做;

...and implement your members elsewhere, while in C#, you'd need to do;

public  memberA() { ...implement your function here... }
public  memberB() { ...implement your function here... }
private memberC() { ...implement your function here... }

关于属性,将它们视为自动实现的 set get 方法,您可以选择自行实现或让编译器实现它们.如果您想自己实现它们,则仍然需要使用字段来存储数据,如果将其留给编译器,它也会生成该字段.

As for properties, see them as auto implemented set and get methods which you can choose to implement yourself or have the compiler implement them. If you want to implement them yourself, you'll still need the field to store your data in, if you leave it up to the compiler, it will also generate the field.

继承的工作原理与将事物放在同一文件中时完全相同(对于较大的C ++项目,这甚至可能不是一个好主意).只要像往常一样继承,只要您在同一名称空间中或导入基类的名称空间,就可以无缝继承;

Inheritance works exactly the same as it would if you put things in the same file (which is probably not even a good idea for bigger C++ projects). Just inherit as usual, as long as you're in the same namespace or have the namespace of the base class imported, you can just inherit seamlessly;

using System.Collections;  // Where IEnumerable is defined

public class MyEnumerable : IEnumerable {  // Just inherit like it 
   ...                                     // was in the same file.
}

这篇关于C#是否像C ++一样使公共/私有之后的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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