Last active
August 16, 2019 16:10
-
-
Save savaged/f973aebc6cefb9b134f8ee6a57aa2af4 to your computer and use it in GitHub Desktop.
Just a quick referencce on defining and using a custom bool like Attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Savaged.Sandpit | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var models = new List<IBaseModel> | |
{ | |
new FirstModel(), | |
new SecondModel() | |
}; | |
foreach (var model in models) | |
{ | |
var attribs = model.GetType() | |
.GetCustomAttributes(typeof(AtomicAttribute), true); | |
bool isAtomic = attribs.FirstOrDefault() | |
is AtomicAttribute attrib | |
? (bool)attrib : false; | |
Console.WriteLine($"{model.GetType().Name} {Convert(isAtomic)} atomic"); | |
} | |
Console.ReadLine(); | |
} | |
static string Convert(bool value) | |
{ | |
return value ? "is" : "is not"; | |
} | |
} | |
public class AtomicAttribute : Attribute | |
{ | |
public AtomicAttribute() | |
{ | |
Value = true; | |
} | |
public bool Value { get; } | |
public static implicit operator bool(AtomicAttribute value) | |
{ | |
if (value is null) | |
{ | |
return false; | |
} | |
return value.Value; | |
} | |
public static explicit operator AtomicAttribute(bool value) | |
{ | |
if (!value) | |
{ | |
return null; | |
} | |
return new AtomicAttribute(); | |
} | |
} | |
public interface IBaseModel | |
{ | |
string Name { get; set; } | |
} | |
public abstract class BaseModel : IBaseModel | |
{ | |
public string Name { get; set; } | |
} | |
public class FirstModel : BaseModel | |
{ | |
} | |
[Atomic] | |
public class SecondModel : BaseModel | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment