更新 #2 - 谜团解开
我已经弄清楚了这个问题 - 这是我在 java 内部类中使用关键字static时的误解。我认为静态意味着传统意义上的静态 - 就像 c# 一样。在 Java 中,静态内部类的含义略有不同。我个人会使用 static 以外的不同关键字来达到相同的效果来消除混淆。
这里有几个很好的链接,它们解释了 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;
}
Run Code Online (Sandbox Code Playgroud)
但是我不能在 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;
}
Run Code Online (Sandbox Code Playgroud)
}
因为在 C# 中无法创建静态类型的实例。
您可以直接访问c#中静态类型的方法和属性。
访问静态类成员
Staticclass.PropetyName;
Staticclass.methodName();
Run Code Online (Sandbox Code Playgroud)
静态类
public static Staticclass
{
public type PropetyName { get ; set; }
public type methodName()
{
// code
return typevariable;
}
}
Run Code Online (Sandbox Code Playgroud)
因此不需要创建 Static 类型的实例,根据 C# 语言语法这是非法的。
| 归档时间: |
|
| 查看次数: |
2239 次 |
| 最近记录: |