Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

.net 3.5 - Error when using extension methods in C#

I came across an issue that makes me think there is bug in the 3.0 framework. When I try to use extension methods I get the following error:

Missing compiler required member
'System.Runtime.CompilerServices.ExtensionAttribute..ctor'

When using this simple code:

public static class StringUtils {
    static void TestExtension(this String targetString) {

    }
}

The only way to make this compile error go away is to add the following code:

namespace System.Runtime.CompilerServices {
    public class ExtensionAttribute : Attribute { }
}

It's been a few months since I have used extensions methods, but I'm pretty sure I didn't have to do this. Has anyone else come across this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have the exact same problem. The error System.Runtime.CompilerServices.ExtensionAttribute..ctor is rather cryptic, and could mean a number of different things.

However, for me It boiled down to the fact that I'm using Newtonsoft.Json.Net. I removed the reference to the file Newtonsoft.Json.Net20.dll, and the re-added it. After this my solution builds again.

The strangest thing is that when I tried to find out what was different after this procedure by using Subversion Diff, nothing appears to have changed.

So I really don't know what removing and re-adding this reference really does, but it does fix my build issue with this particular error message mentioned by the asker.

UPDATE 1:

For those that come across this again, as the comenters pointed out, the proper way to fix this is to Download Json.Net's ZIP, and there should be a 3.5 version, re-reference 3.5 every where you are using Json.Net and delete the old reference, as it is likely referencing an assembly that was built for older versions of .net.

UPDATE 2:

Charlie Flowers points out that the DLL NewtonSoft labels as being for 3.5 is actually not going to work with 3.5. You have to use the DLL they label as being for .net 2.0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...