开发者

How can I pass a runtime method to a custom attribute or viable alternative approach

开发者 https://www.devze.com 2023-01-19 14:20 出处:网络
Basically I would like to do something like this at the top of my class (I know this doesn\'t work as it isn\'t a constant)....

Basically I would like to do something like this at the top of my class (I know this doesn't work as it isn't a constant)....

[XmlStorage(IsSingleStorageFile = false, IsSubordinate = true, StorageLocation = "posts" + GetBlogId()]

Where GetBlogId() would be a static utility method.

I'm building an xml storage framework for a blogging engine I am writing (partly a learning excercise, partly as I want to give something back to the open source) and I thought that the tidiest way to determine the storage location would be to use custom attributes since I would be to use a datacontr开发者_开发问答actserializer anyway.

My only problem at present is determining the location for subordinate type whose location would be determined by the id of their parent. e.g Post < Blog.

My storage path would be something like this...

posts\blogid\postid.xml

Where the blog id would be determined by parsing the url and returning the associated blog. This would allow me to host multiple blogs in one installation whilst keeping post storage files separate to reduce memory overheads when loading posts.

Is this a straight no or is there a better way for me to do what I am attempting?

Edit:

Following John answer I tried this....

 private static string GetSubordinatePath(Type type)
    {
        if (typeof(ISubordinate).IsAssignableFrom(type))
        {
            object instance = Activator.CreateInstance(type);
            return (instance as ISubordinate).ParentGuid.ToString();
        }
        else
        {
            // TODO: Localize this.
            throw new ArgumentException(
            String.Format(
            CultureInfo.CurrentCulture,
            "The specified type '{0}' does not impliment the ISubordinate interface. Please edit the source appropriately to enable storage.",
            type.GetType().Name));
        }
    }

Which would be called from the class reading the custom attribute.

This works nicely..


It's a straight no for attributes... the values are constants baked into the metadata.

One option you could use would be to have some sort of templating built into whatever uses the attributes... so you could have a storage location of posts\{GetBlogId()} and call the method at execution time. It's not exactly elegant though... you might want to consider using an interface instead.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号