gpt4 book ai didi

c# - 通用属性缺点?

转载 作者:太空狗 更新时间:2023-10-29 22:28:28 26 4
gpt4 key购买 nike

我在我的项目中使用了通用属性,但我不知道,使用它们有什么缺点吗,请告诉我一个场景,它们有缺点吗?下面是我的部分代码。

public class GenericResult<T>
{
public T Data { get; set; }
public bool IsSuccess { get; set; }
public string Message { get; set; }
}

public GenericResult<int> AddCategory(TCategory tCategory)
{
GenericResult<int> result = new GenericResult<int>();

//business logic validation,dont make sense,only example :)
if (tCategory.Name.Lenght > 100)
{
result.IsSuccess = false;
result.Message = "Category Name length is too long";
result.Data = 0;
}

//handle .net runtime error//may be database is not aviable.
try
{
result.Data = this.catalogRepository.AddCategory(tCategory);
result.IsSuccess = true;
}
catch (Exception ex)
{
result.Data = 0;
result.IsSuccess = false;
result.Message = ex.Message;
}
return result;
}

public GenericResult<IEnumerable<TCategory>> GetCategoryHierarchy(TCategory parentCategory)
{
GenericResult<IEnumerable<TCategory>> result = new GenericResult<IEnumerable<TCategory>>();
try
{
IEnumerable<TCategory> allCategories = catalogRepository.GetAllCategories();
result.Data = GetCategoryHierarchy(allCategories, parentCategory);
result.IsSuccess = true;

}
catch (Exception ex)
{
result.IsSuccess = false;
result.Data = null;
result.Message = ex.Message;
}
return result;
}

最佳答案

如果您不想抛出异常,但更愿意返回包含错误或值的结果,即 MayBe在某些情况下这很好。但老实说,在这种情况下,我更愿意简单地抛出/传递异常。

我更愿意返回一个不可变的结构作为 MayBe而不是像你那样的可变类。它与 Nullable<T> 非常相似,除了它适用于引用类型并且可以存储错误。像这样的东西:

public struct MayBe<T>
{
private T value;
private Exception error;

public bool HasValue{get{return error==null;}}
public T Value
{
if(error!=null)
throw error;
else
return value;
}

public static MayBe<T> CreateError(Exception exception)
{
return new MayBe<T>(default(T),exception);
}

public static MayBe<T> CreateValue(T value)
{
return new MayBe<T>(value,null);
}

public static implicit operator MayBe<T>(T value)
{
return CreateValue(value);
}

public override string ToString()
{
if(HasValue)
return "Value: "+Value.ToString();
else
return "Error: "+Error.GetType().Name+" "+Error.Message;
}
}

你的代码变成了

public MayBe<int> AddCategory(TCategory tCategory)
{
try
{
return this.catalogRepository.AddCategory(tCategory);
}
catch (Exception ex)
{
return MayBe<int>.CreateError(ex);
}

return result;
}

public MayBe<IEnumerable<TCategory>> GetCategoryHierarchy(TCategory parentCategory)
{
try
{
IEnumerable<TCategory> allCategories = catalogRepository.GetAllCategories();
return allCategories;

}
catch (Exception ex)
{
return MayBe<int>.CreateError(ex);
}

return result;
}

我发现此实现的一个问题是异常并非完全不可变。如果相同 MayBe<T> 可能会导致问题抛出多个线程。也许有人可以提出更好的实现建议。

关于c# - 通用属性缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5919700/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com