更新#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