难道Java的有"性能"该工作方式相同的属性在C#中工作? [英] Does Java have "properties" that work the same way properties work in C#?

查看:150
本文介绍了难道Java的有"性能"该工作方式相同的属性在C#中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,可以使用属性,使一个数据字段公开访问(允许用户直接访问它),但保留对那些直接访问的字段执行数据验证的能力。是否有Java的类似的东西?例如,假设存在与以下实现C#类(见下文):

In C#, you can use properties to make a data field publicly accessible (allowing the user to directly access it), and yet retain the ability to perform data validation on those directly-accessed fields. Does Java have something similar? For Instance, suppose there exists a C# class with the following implementation(see below):

public class newInt{

    public newInt(){...}

    public int x{
        get{ return this.x }
        set{ this.x = isValid(value) }
    }
}

private static int isValid(int value){...}

这个定义在类允许用户自然地从它检索值,并把它分配值时所使用的数据字段的x。下面是如何,将在主要被使用。

This definition in the class allows the user to "naturally" use the data field 'x' when retrieving values from it and assigning values to it. Below is how it would be used in main.

public class Test{

    public static void main(String[] args){

        newInt a = new newInt();
        a.x = 50;

        int b = a.x;
    }
}



问题是......可以用java做这个作为好?如果是这样,那是什么叫什么?

The question is... can java do this as well? if so, what is it called?

推荐答案

没有。

这就是为什么Java有getter / setter方法​​

That's why Java has getters/setters.

在C#中,通常情况下是这样的:

In C# you typically have something like:

public class SomeObject
{
    private string _title = "";

    public string Title { get { return _title; } set { _title = value; } }
}

// Or with Auto-Properties
public class SomeObjectAutoProperties
{
    public string Title { get; set; }
}



在Java的getter / setter相当于将是:

The Java getter/setter equivalent would be:

public class SomeObject
{
    private String _title = "";

    public string getTitle() { return _title; }

    public void setTitle(String value) { _title = value; }
}

这篇关于难道Java的有"性能"该工作方式相同的属性在C#中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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