是否有这样的可能?我假设不是,但它看起来不错对我说:属性支持值范围
class MyClass {
public int Foo {
get { return m_foo; }
set {
// Bounds checking, or other things that prevent the use
// of an auto-implemented property
m_foo = value;
}
// Put the backing field actually *in* the scope of the property
// so that the rest of the class cannot access it.
private int m_foo;
}
void Method() {
m_foo = 42; // Can't touch this!
}
}
我当然知道这个语法是不正确的,这将无法编译。为了清晰地表达我的想法,这是假想的未来-C#。我对这个有点假设的问题表示歉意,但对程序员来说太具体了。
类似这样的东西可以在编译器中实现,它可以用于一个目的:只允许属性的get
和set
访问器查看字段,实质上允许该属性是自包含的(作为自动实现的属性),而允许额外的获取/设置逻辑。
这是一个简单的是/否的问题(因为那样很** **无),或者你想替代解决这个‘问题’? –
我只是好奇你想通过这样做达到什么目的? –
备用解决方案将会非常有趣。强制使用属性而不是类中的变量可能是一个很好的功能。因为这一定是目标,对吧? –