限制类成员的范围超出私有

我想知道是否有办法专门访问类成员的访问权限来获取/设置c#中的实现,以减少我不小心直接访问它们的机会。 像private这样的东西只允许get / set访问它,我想我可以将每个变量包装在他们自己的类中,但这对于我正在寻找的限制来说似乎有些过分。 谢谢

不,不幸的是没有。 我假设你会追求这样的事情:

// Not actually valid C#! public string Name { // Only accessible within the property string name; get { return name; } set { if (value == null) { throw new ArgumentNullException(); } name = value; } } 

我之前也想要这样的东西。 不幸的是,这是不可能的:(

您可以在字段中添加[Obsolete("Use the property")]并通过编写#pragma warning disable 618来抑制属性中的#pragma warning disable 618

这是不可能的。 唯一的访问修饰符是privateinternalprotectedprotected internalpublic并且没有一个适合账单。

但是,如果您使用自动属性,那么您当然只能通过get和set访问它。

如果您不需要在访问器中执行任何操作,请使用自动实现的属性 。

我猜你最有可能想做操作,这就是为什么你要确保你使用属性而不是支持字段。

在这种情况下考虑以下内容:

  • 使用“_instanceName”之类的命名约定来表示私有成员字段。 (无论如何你应该这样做……)
  • 当您认为访问器内的操作很常见且可重用时,请将其封装在类中。 在遇到性能问题之前,不要担心过度杀伤。

我相信我可能已经找到了一种可能的解决方法,而且它的结果非常小。 然而,这种“解决方案”可能有点过于聪明。 也许明天我会做一些基准测试。 问题是目前它的范围也在它使用的每个地方,也许通过使用generics,这可能是有限的。

它利用了lambda始终具有相同的支持方法的事实。 通过将lambda传递给静态构造函数,静态对象可以跟踪这个唯一的“范围”并将变量链接到它。 有关此实现的更多详细信息,请参见此处 。

用法:

 class LocalTestClass { public int StaticTest( int setValue ) { Local test = Local.Static( () => { } ); int before = test.Value; test.Value = setValue; return before; } public int InstanceTest( int setValue ) { Local test = Local.Instance( () => this ); int before = test.Value; test.Value = setValue; return before; } } [TestMethod] public void LocalStaticTest() { LocalTestClass instance1 = new LocalTestClass(); LocalTestClass instance2 = new LocalTestClass(); instance1.StaticTest( 10 ); Assert.AreEqual( 10, instance2.StaticTest( 20 ) ); Assert.AreEqual( 20, instance1.StaticTest( 30 ) ); } [TestMethod] public void LocalInstanceTest() { LocalTestClass instance1 = new LocalTestClass(); LocalTestClass instance2 = new LocalTestClass(); instance1.InstanceTest( 10 ); Assert.AreEqual( 10, instance1.InstanceTest( 20 ) ); instance2.InstanceTest( 50 ); Assert.AreEqual( 20, instance1.InstanceTest( 30 ) ); } 

class级:

 public class Local { static readonly Dictionary StaticScope = new Dictionary(); static readonly Dictionary> InstanceScope = new Dictionary>(); public TValue Value { get; set; } private Local() { } public static Local Static( Action scope ) { if ( !StaticScope.ContainsKey( scope ) ) { Local newInstance = new Local(); StaticScope.Add( scope, newInstance ); } return StaticScope[ scope ] as Local; } public static Local Instance( Func scope ) { object instance = scope(); if ( !InstanceScope.ContainsKey( instance ) ) { InstanceScope.Add( instance, new Dictionary() ); if ( !InstanceScope[ instance ].ContainsKey( scope ) ) { Local newInstance = new Local(); InstanceScope[ instance ].Add( scope, newInstance ); } } return InstanceScope[ instance ][ scope ] as Local; } } 

有关此主题的更一般性讨论可以在Programmers.SE上找到 。