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

标签 c# java static

更新 #2 - 解开谜题

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

这里有几个很好的链接,解释了静态内部类在 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

这是一个如何使用此模式优化自定义列表适配器的示例。如您所见,我不能只通过静态类名访问静态成员,而是需要通过变量来引用它。它需要传递给标签。

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/

相关文章:

java - 从不可见的 AWT 组件创建图像?

javascript - 如何从 Django 加载模型管理文件中的静态文件?

C++ 初始化静态数组

c# - 一起使用事件驱动的 TCP 客户端和 NotifyPropertyChanged 会导致异常

c# - Visual Studio 近期项目列表

java - 如果 tomcat 作为 Windows 服务托管,tomcat8.exe 会消耗大量 CPU/内存

java - 分形噪声地形产生奇怪的人工制品线

c# - 提交按钮在 asp.net mvc 中不起作用

c# - 如何根据注入(inject)上下文自定义注入(inject)实例?

routes - 如果目标设置为 'static',Nuxt.js 路由中间件问题