更新#2 - 神秘现象声明静态类型的成员在C#
我必须弄明白的问题 - 是在Java内部类使用的时候,这是我的关键字静态的误解。我认为静态意味着传统意义上的静态 - 与c#一样。在Java的情况下,静态内部类的含义略有不同。我个人会使用除静态以外的其他关键字来达到相同的效果以消除混淆。
这里有几个很好的链接可以解释java中静态内部类的含义。
对不起发送白费力气:)
原贴大家
在java中我可以写:
public class UseStaticMembers {
private Holder holder;
holder.txt1 = "text";
holder.txt2 = "text";
CallSomeMethod(holder);
}
static class Holder {
public string txt1;
public string txt2;
}
但我不能在C#中执行此操作。我得到以下错误:“不能声明一个静态类型'持有人'的变量:”私人持有人持有人;“我如何在C#中实现相同的效果(如果可以的话)。
更新#1
下面是这种图案是如何用于优化自定义列表适配器的示例。正如你所看到的,我不能通过静态类名访问静态成员,但需要通过变量引用它。它需要传递给标签。
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
holder.imgIcon.setImageResource(weather.icon);
return row;
}
static class WeatherHolder
{
ImageView imgIcon;
TextView txtTitle;
}
}
如果你想要一个'Holder'的实例,为什么要使它成为'static'? – 2012-02-24 16:22:51
@IUnknown你应该知道静态和实例成员之间有什么区别。他们是不同的。 – nawfal 2012-02-24 16:23:57
你试图实现什么样的效果? - 也就是说,在java中以这种方式使用静态类属性是做什么的一个实例属性不? – 2012-02-24 16:23:58