更新 #2 - 解开谜题
我已经弄清楚了问题 - 这是我在 java 内部类中使用时对关键字 static 的误解。我认为 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;
}
但我不能在 C# 中执行此操作。我收到以下错误:“无法声明静态类型 'Holder' 的变量”行:“private Holder holder;”
如何在 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;
}
最佳答案
因为您不能在 C# 中创建静态类型的实例。
在c#中可以直接访问静态类型的方法和属性。
访问静态类成员
Staticclass.PropetyName;
Staticclass.methodName();
静态类
public static Staticclass
{
public type PropetyName { get ; set; }
public type methodName()
{
// code
return typevariable;
}
}
所以没有必要创建静态类型的实例,根据C#语言语法这是非法的。
关于c# - 在c#中声明一个静态类型的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9434197/