简体   繁体   中英

How do I cast a generic value at runtime in C#?

I have a generic struct which is like

public struct Range<T>

and has two properties, From and To of type T .

The struct also has a member like:

public bool FromGreaterTo
{
    get { return (bool)Comparer<T>.Default.Compare(From, To) > 0 };
}

I create a ValidationAttribute for properties of this struct.

In the override of the IsValid method I do know that it is of Type Range<> and T is int? or whatever.

How can I dynamically cast the value parameter (which is actually the Range<> property) so I can access the FromGreaterTo member?

I already tried something like

private Range<T> Cast<T> (object valueToCast, T genericType)
{
    return (Range<T>)valueToCast;
}

which throws an exception, that this cast is invalid.

Any ideas or workarounds on that?

Make Range a class and give it an abstract base class.

public abstract class Range
{
    public abstract bool FromGreaterTo { get; }
}

public class Range<T> : Range
{
    // existing Range<T> code
}

Then you can just cast your Range<T> object to a Range object and call its FromGreaterTo property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM