我在构造函数中调用一个方法,如below.Is,这是根据某些validations.Please建议设置属性的正确方法。
public class Asset
{
public Asset(string id)
{
SetStorageId(id);
}
public string AssetId { get; set; }
public string UtilId { get; set; }
public string MappingId { get; set; }
public bool IsActive { get; set; }
private void SetStorageId(string id)
{
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
AssetId = id;
}
else
{
UtilId = id;
}
}
}发布于 2017-12-20 07:07:17
简单地试试这个
public class Asset
{
private string id;
public string AssetId { get; set; }
public string UtilId { get; set; }
public string Id
{
set
{
if (Regex.Match(value, "^[A-Z][a-zA-Z]*$").Success)
{
this.id = value;
}
else
{
UtilId = value;
}
}
get
{
return id;
}
}
}在c#中创建属性时,将在编译时为该属性创建一个私有变量。当您试图在上面的代码中设置Id属性时,您传递的Id将进入value关键字,您可以对value关键字执行验证,并相应地设置属性。不需要使用set方法、构造函数或派生类来使代码复杂化。
或者您甚至可以使用数据注释,这是一种更优雅的https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx#Properties方式。
using System.ComponentModel.DataAnnotations;
public class Asset
{
[RegularExpression("^[A-Z][a-zA-Z]*$")]
public string Id { get; set; }
}发布于 2017-12-20 05:09:34
我认为你的设计应该如下所示,
您应该将公共项抽象为基类,并创建继承它的特定类,
并从客户端(使用者)决定您需要哪个实例并构造它。
public class AssetBase
{
public string MappingId { get; set; }
public bool IsActive { get; set; }
}
public class Asset : AssetBase
{
public string AssetId { get; set; }
}
public class Util : AssetBase
{
public string UtilId { get; set; }
}
static void Main(string[] args)
{
string id = Console.ReadLine();
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
Asset asset = new Asset();
asset.AssetId = id;
}
else
{
Util util = new Util();
util.UtilId = id;
}
}发布于 2017-12-20 06:37:31
这没什么错。它可能会变得有点混乱。也许您可以通过将SetStorageId的bod移动到构造函数来使其更加清晰。相对于项目中的其他代码,也许没有必要将子类复杂化。
https://stackoverflow.com/questions/47899022
复制相似问题