C#如何分配静态类的默认属性值 [英] C# How to assign default property value of static class

查看:57
本文介绍了C#如何分配静态类的默认属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C# 中分配静态类的默认属性值?我正在尝试执行以下操作:

how can I assign default property value of static class in C#? I'm trying to do followings:

public class Unit
{
  public string Name;
  public double cConvertFromSI;
}

// want to do something like this:
public static Unit m  = (Name = "meter"; cConvertFromSI = 1;)
public static Unit mm = (Name = "millimeter"; cConvertFromSI = 1000;)
public static Unit in = (Name = "inch"; cConvertFromSI = 39.3701;)

推荐答案

首先,不要使用公共字段,使用带有 getter/setter 的属性,它会破坏封装.其次,您应该实例化 Unit 的对象并初始化属性.查看一些示例:

First thing, do not use public fields, use properties with getters/setters, it will break the encapsulation. Second, you should instance an object of Unit and initialize the properties. See some examples:

public class Unit
{
  public string Name { get; set; }
  public double cConvertFromSI { get; set; }
}

public static Unit m  = new Unit() { Name = "meter", cConvertFromSI = 1 };
public static Unit mm = new Unit() { Name = "millimeter", cConvertFromSI = 1000 };
public static Unit in = new Unit() { Name = "inch", cConvertFromSI = 39.3701 };

这篇关于C#如何分配静态类的默认属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆