我可以仅使用 C# 中的对象名称访问对象 属性 吗?

Can I access an object property just with the object name in C#?

我有一个简单的 class,其中包含一些私有属性和 2 个 public 属性(值和类型)。我试图找到一种方法来调用该对象,使其 returns 其值 属性 而不必调用 obj.value。我觉得不可能。

这是我的想法:

public class myclass {
   private int property1;
   private int property2;
   public string value;
   public string type;

   public myclass(int property1, int property2, string value, string type)
   {
       this.property1 = property1;
       this.property2 = property2;
       this.value = value;
       this.type = type;
   }
}

var obj = new myclass(1, 2, "abc", "string");
console.write(obj.value);   // returns abc
console.write(obj.type);   // returns string
console.write(obj);    // expecting abc

最后一行 returns abc 有没有办法使用这种语法?

你问我为什么要达到这样的目的?我正在构建一个带有 Javascript 编程模块的服务。这些对象是变量,我希望用户通过简单地编写 obj 而不是 obj.value 来访问它们。我在 C# 中需要这种行为(而不是 Javascript),因为 Javascript 正在回调后端对象。如果我不必保留私有财产那会很容易,但我需要拥有它们。

更新: 为了更清楚:这个 class 将由 Javascript 解释器(在本例中为 Jint)调用,并且 class 必须在其值更新时更新数据库,所以私有财产的需要。 这是我的实际代码:

public class SmartNumeric : ISmartVariable
{
    private Boolean _simulation;
    private Guid UserId;
    private long userKeyId;
    private long variableKeyId;
    private string Name;
    public string type
    {
        get {
            return "numeric";
        }
    }
    private float _value;
    public float value
    {
        get {
            return _value;
        }

        set {
            _value = value;

            if (!_simulation)
                new SmartCommon().SetValue(userKeyId, variableKeyId, value.ToString());
        }
    }

    public SmartNumeric(Guid UserId, long userKeyId, long variableKeyId, string Name, float value, Boolean simulation)
    {
        this.Name = Name;
        this._value = value;
        this.UserId = UserId;
        this.userKeyId = userKeyId;
        this.variableKeyId = variableKeyId;
        this._simulation = simulation;
    }
}

例如,用户将编写自己的脚本,例如

a = 45;

Javascript 比

更自然
a.value = 45;

其中 a 指代 C# 中的 SmartNumeric 对象。对象收到更新,这是我需要返回数据库更新值并需要其他属性的地方。

是的,您可以将 MyClass 中的 ToString 方法重写为 return 您想要的 属性 的值,例如

public override string ToString()
{
    return this.value;
}

将此添加到您的 class,最后一行将显示您 "abc"

注意:这里发生的是,基本上当您调用 Console.WriteLine(<Something>) 时,它会尝试调用 class 对象中的 ToString() 方法。现在我们知道对象 class 是我们拥有的任何 class 的超级 Class。因此,我们覆盖了 ToString() 方法,并且我们 return 我们想要从 class.

中 return 的任何字符串

你的最后一行必须是 Console.WriteLine(obj.ToString()).

希望对您有所帮助!

最后的答案是,做不到。变量是变量,对象是对象。试图摆脱它并作弊只会带来其他问题,而且我看不出如何将其他属性与变量相关联而不使其成为对象。所以它必须是一个对象,并且将使用 obj.value.

访问该值