微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在c#中声明静态类型的成员

更新#2 – 解决了谜团

我已经弄清楚了这个问题 – 这是我在java内部类中使用时对关键字static的误解.我认为静态意味着传统意义上的静态 – 就像c#一样.在Java的情况下,静态内部类具有略微不同的含义.我个人会使用除静态之外的其他关键字来达到相同的效果以消除混淆.

这里有几个很好的链接,解释了静态内部类在java中的含义.

link1
link2

对不起发送每个人的野鹅追逐:)

原帖

在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

以下是此模式如何用于优化自定义列表适配器的示例.如您所见,我不能通过静态类名访问静态成员,但需要通过变量引用它.它需要传递给Tag.

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#语言语法,这是非法的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐