C# C Sharp 中“朋友”关键字的等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/445490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the equivalent of a 'friend' keyword in C Sharp?
提问by xarzu
What is the equivalent of a 'friend' keyword in C Sharp?
C Sharp 中“朋友”关键字的等价物是什么?
How do I use the 'internal' keyword?
如何使用“内部”关键字?
I have read that 'internal' keyword is a replacement for 'friend' in C#.
我读过“内部”关键字是 C# 中“朋友”的替代品。
I am using a DLL in my C# project that I have the source code for and yet I do not want to modify the existing code. I have inherited the class and I can use my inherited class any way I want. The problem is that most of the code in the parent class has protected methods. Will using a friend somehow make it possible to access or call these protected methods?
我在我的 C# 项目中使用了一个 DLL,我有它的源代码,但我不想修改现有代码。我已经继承了这个类,我可以以任何我想要的方式使用我继承的类。问题是父类中的大部分代码都有受保护的方法。使用朋友是否可以以某种方式访问或调用这些受保护的方法?
采纳答案by jason
You can use the keyword access modifier
internal
to declare a type or type member as accessible to code in the same assembly only.You can use the
InternalsVisibleToAttribute
class defined inSystem.Rutime.CompilerServices
to declare a type as accessible to code in the same assembly or a specified assembly only.
您可以使用关键字访问修饰符
internal
将类型或类型成员声明为仅可由同一程序集中的代码访问。您可以使用 中
InternalsVisibleToAttribute
定义的类将System.Rutime.CompilerServices
类型声明为只能在同一程序集中或指定程序集中的代码中访问。
You use the first as you use any other access modifiersuch as private
. To wit:
您可以像使用任何其他访问修饰符一样使用第一个,例如private
. 以机智:
internal class MyClass {
...
}
You use the second as follows:
您可以按如下方式使用第二个:
[assembly:InternalsVisibleTo("MyFriendAssembly", PublicKey="...")]
internal class MyVisibleClass {
...
}
Both of these can rightly be considered the equivalent of friend
in C#.
这两者都可以正确地被视为friend
C# 中的等价物。
Methods that are protected
are already available to derived classes.
protected
派生类已经可用的方法。
回答by johnc
internal
is the C# equivalent of the VB.NETfriend
keyword, as you have guessed (as opposed to a replacement)Usage is as follows
internal void Function() {} internal Class Classname() {} internal int myInt; internal int MyProperty { get; set; }
It, basically, is an access modifier that stipulates that the accessibility of the class / function / variable / property marked as internal is as if it were public to the Assembly it is compiled in, and private to any other assemblies
internal
是 C# 中 VB.NETfriend
关键字的等价物,正如您所猜测的(而不是替代品)用法如下
internal void Function() {} internal Class Classname() {} internal int myInt; internal int MyProperty { get; set; }
它基本上是一个访问修饰符,它规定标记为内部的类/函数/变量/属性的可访问性就好像它对编译它的程序集是公开的,而对任何其他程序集是私有的
回答by Jon B
Internal is the equivalent of friend. A protected method is only available within the same class or from an inheritor. If you're trying to expose protected methods from an inheritor, you can wrap them in public methods.
内部相当于朋友。受保护的方法仅在同一类中或从继承者中可用。如果您尝试从继承者公开受保护的方法,您可以将它们包装在公共方法中。
回答by strager
Your subclass will be able to access the protected members of the class you inherit.
您的子类将能够访问您继承的类的受保护成员。
Are you looking to give access to these protected members to another class?
您是否希望将这些受保护成员的访问权限授予另一个类?
回答by Harley2000
No, "internal" is not the same as "friend" (at least the C++ 'friend')
不,“内部”与“朋友”不同(至少是 C++ 的“朋友”)
friend specifies that this class is only accessible by ONE, particular class.
internal specifies that this class is accessible by ANY class in the assembly.
朋友指定这个类只能由一个特定的类访问。
internal 指定该类可由程序集中的任何类访问。
回答by mushi
Here's a weird trick I used for adding behaviour akin to C++'s friend
keyword. This only works for nested classes AFAIK.
这是我用来添加类似于 C++friend
关键字的行为的奇怪技巧。这仅适用于嵌套类 AFAIK。
- Create a nested
protected
orprivate
interface with the variables you'd like to give access to via properties. - Let the nested class inherit this interface and implement it explicitly.
- Whenever using an object of this nested class, cast it to the interface and call the respective properties.
- 使用您希望通过属性访问的变量创建一个嵌套
protected
或private
接口。 - 让嵌套类继承这个接口并显式地实现它。
- 每当使用此嵌套类的对象时,将其转换为接口并调用相应的属性。
Here's an example from Unity.
这是来自 Unity 的示例。
using System;
using UnityEngine;
using UnityEngine.Assertions;
namespace TL7.Stats
{
[CreateAssetMenu(fileName = "Progression", menuName = "TL7/Stats/New Progression", order = 0)]
public class Progression : ScriptableObject
{
// Provides access to private members only to outer class Progression
protected interface IProgressionClassAccess
{
CharacterClass CharacterClass { get; set; }
}
[System.Serializable]
public struct ProgressionClass : IProgressionClassAccess
{
[Header("DO NOT EDIT THIS VALUE.")]
[SerializeField] private CharacterClass characterClass;
[Tooltip("Levels are 0 indexed.")]
[SerializeField] float[] healthOverLevels;
public float[] HealthOverLevels => healthOverLevels;
CharacterClass IProgressionClassAccess.CharacterClass
{
get => characterClass;
set => characterClass = value;
}
}
static readonly Array characterClasses = Enum.GetValues(typeof(CharacterClass));
[SerializeField] ProgressionClass[] classes = new ProgressionClass[characterClasses.Length];
public ProgressionClass this[in CharacterClass index] => classes[(int)index];
void Awake()
{
for (int i = 0; i < classes.Length; ++i)
{
// Needs to be cast to obtain access
(classes[i] as IProgressionClassAccess).CharacterClass = (CharacterClass)characterClasses.GetValue(i);
}
}
#if UNITY_EDITOR
public void AssertCorrectSetup()
{
for (int i = 0; i < characterClasses.Length; ++i)
{
CharacterClass characterClass = (CharacterClass)characterClasses.GetValue(i);
Assert.IsTrue(
(this[characterClass] as IProgressionClassAccess).CharacterClass == characterClass,
$"You messed with the class values in {GetType()} '{name}'. This won't do."
);
}
}
#endif
}
}
I think this only works for nested classes. In case you want to do this with regular classes, you'd need to nest them inside a partial outer class, which should work in theory, and use a protected
or private
nested interface (or two, if you're inclined) for providing them access to each other's privates... that came out wrong.
我认为这仅适用于嵌套类。如果您想对常规类执行此操作,则需要将它们嵌套在部分外部类中,理论上应该可以工作,并使用一个protected
或private
嵌套的接口(或两个,如果您愿意)为它们提供访问权限彼此的隐私……结果错了。
回答by AvrDragon
Splitting a big class in two partial class-files can achive the desired friend-effect. It is not equivalent, but it works in some cases.
将一个大类拆分为两个部分类文件可以实现所需的朋友效果。它不是等价的,但它在某些情况下有效。