C#类中的可选属性 [英] Optional property in a C# class
本文介绍了C#类中的可选属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Optional property
I want to create a class that has an optional property. I don't want to create a subclass
Example
public class MyClass
{
public MyClass( int extraPoperty)
{
// Something like this
if(extraPoperty==1)
public int ExtraPoperty { get; set; }
}
public int EntityId { get; set; }
}
Is this possible?
我尝试过:
我在网上找不到任何东西
What I have tried:
I can not find anything on the web
推荐答案
不 - 你不能在方法或构造函数中定义一个属性,仅在类体内。
你究竟想做什么?为什么你认为你需要这个?
No - you can't define a property within a method or constructor, only within the class body.
What exactly are you trying to do? Why do you think you need this?
最好的赌注可能是一个可以为空的领域
Best bet is probably a nullable field
public int? MyProperty {get;set;}
如果该字段为空,您可以认为它尚未提供。
If the field is null you can assume it hasn't been supplied.
不可能,你的财产是否定义,它不能是有条件的。
但你可以dynamic
类ExpandoObject
:
使用Type dynamic(C#编程指南)| Microsoft Docs [ ^ ]
system.dynamic.expandoobject [ system.dynamic.expandoobject ] < br $> b $ b
创建动态,可扩展的C#Expando对象 - Rick Strahl的Web日志 [ ^ ]
No it is not possible, your property is either defined or not, it cannot be conditional.
However you can havedynamic
classes withExpandoObject
:
Using Type dynamic (C# Programming Guide) | Microsoft Docs[^]
system.dynamic.expandoobject[system.dynamic.expandoobject]
Creating a dynamic, extensible C# Expando Object - Rick Strahl's Web Log[^]
这篇关于C#类中的可选属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文